using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System;

public class SettingsHandler : MonoBehaviour{
    /*STEPS
        1. Load PlayerPrefs for Settings, if not available then load default values
        2. If PlayerPrefs are available, then load the Settings UI with the current values
        3. Upon changing a setting, automatically update the PlayerPref associated with that setting

        Sounds
        Vibration
    */
    private GameSettings gameSettings;

    private const string GameSettingsKey = "GameSettings";

    public GameObject popup;


    //Define and Attach all GameObjects that need Positioning and Scaling here, total 6 in other game
    //Left Controls
    public RectTransform leftControlRectTransform; 
    // public RectTransform blockControlRectTransform; // Removed
    // public RectTransform dodgeControlRectTransform; // Removed

    //Right Controls
    // public RectTransform rightControlRectTransform; // Removed
    public RectTransform punchControlRectTransform;
    public RectTransform kickControlRectTransform;

    // New control buttons for unified system
    public RectTransform weaponPickupButtonRectTransform;
    public RectTransform specialMoveButtonRectTransform;
    public RectTransform shieldButtonRectTransform;
    public RectTransform splintButtonRectTransform;
    public Slider[] VolumeSliderArray; //0. GameplayVolume, 1. UIVolume, 2. MusicVolume, 3. SFXVolume
    public TextMeshProUGUI[] VolumeSliderValues; //0. GameplayVolume, 1. UIVolume, 2. MusicVolume, 3. SFXVolume

    // public TextMeshProUGUI lt;

    //For Privacy & Socials
    public Button[] SocialButtons;

    void OnEnable(){
        //If Key is present, then load
        if (PlayerPrefs.HasKey(GameSettingsKey))
        {
            LoadSettings(); //Load
            // ResetControlSettings();
            Debug.Log("Present");


        }else{
            DefaultSettings(); //Set Volume and Controls Settings
            // SaveGameSettings();
        }

        foreach (Button btn in SocialButtons){
            btn.onClick.AddListener(() => OpenSocialsLink((btn.gameObject).name));
        }
    }


    // Function to open a specific social based on User interaction
    void OpenSocialsLink(String SocialsClickedName){
        switch(SocialsClickedName){
            case "facebook":
                //Open Facebook
                Application.OpenURL("https://www.facebook.com/PlayDEVIANT");
                break;

            case "youtube":
                //Open Youtube
                Application.OpenURL("https://www.youtube.com/@PlayDEVIANT");
                break;

            case "instagram":
                //Open Instagram
                Application.OpenURL("https://www.instagram.com/playdeviant/");
                break;

            case "whatsapp":
                //Open Whatsapp
                Application.OpenURL("https://whatsapp.com/channel/0029Va8alUzHgZWdoyh8db1K");
                break;

            case "tiktok":
                //Open Tiktok
                Application.OpenURL("https://www.tiktok.com/@playdeviant");
                break;
        }
    }


    void Start(){
        // DefaultSettings(); //Set Volume and Controls Settings

        //If Key is present, then load
        if (PlayerPrefs.HasKey(GameSettingsKey))
        {
            LoadSettings(); //Load

        }else{
            DefaultSettings(); //Set Volume and Controls Settings
            // SaveGameSettings();
        }
    }


    void DefaultSettings(){
        DefaultControlsSettings();        

        //Reset Volume Settings, Set to Full Volume
        foreach (Slider sld in VolumeSliderArray){
            sld.value = 1f;
        }

        foreach (TextMeshProUGUI txtM in VolumeSliderValues){
            txtM.text = "100%";
        }

        SaveSettings();
    }


    void Update(){

    }


    public void SaveSettings()
    {
        GameSettings settings = new GameSettings
        {
            leftControl = new ControlSettings
            {
                positionX = leftControlRectTransform.anchoredPosition.x,
                positionY = leftControlRectTransform.anchoredPosition.y,
                scaleWidth = leftControlRectTransform.sizeDelta.x,
                scaleHeight = leftControlRectTransform.sizeDelta.y
            },
            punchControl = new ControlSettings
            {
                positionX = punchControlRectTransform.anchoredPosition.x,
                positionY = punchControlRectTransform.anchoredPosition.y,
                scaleWidth = punchControlRectTransform.sizeDelta.x,
                scaleHeight = punchControlRectTransform.sizeDelta.y
            },
            kickControl = new ControlSettings
            {
                positionX = kickControlRectTransform.anchoredPosition.x,
                positionY = kickControlRectTransform.anchoredPosition.y,
                scaleWidth = kickControlRectTransform.sizeDelta.x,
                scaleHeight = kickControlRectTransform.sizeDelta.y
            },

            // New buttons
            weaponPickupButton = new ControlSettings
            {
                positionX = weaponPickupButtonRectTransform.anchoredPosition.x,
                positionY = weaponPickupButtonRectTransform.anchoredPosition.y,
                scaleWidth = weaponPickupButtonRectTransform.sizeDelta.x,
                scaleHeight = weaponPickupButtonRectTransform.sizeDelta.y
            },
            specialMoveButton = new ControlSettings
            {
                positionX = specialMoveButtonRectTransform.anchoredPosition.x,
                positionY = specialMoveButtonRectTransform.anchoredPosition.y,
                scaleWidth = specialMoveButtonRectTransform.sizeDelta.x,
                scaleHeight = specialMoveButtonRectTransform.sizeDelta.y
            },
            shieldButton = new ControlSettings
            {
                positionX = shieldButtonRectTransform.anchoredPosition.x,
                positionY = shieldButtonRectTransform.anchoredPosition.y,
                scaleWidth = shieldButtonRectTransform.sizeDelta.x,
                scaleHeight = shieldButtonRectTransform.sizeDelta.y
            },
            splintButton = new ControlSettings
            {
                positionX = splintButtonRectTransform.anchoredPosition.x,
                positionY = splintButtonRectTransform.anchoredPosition.y,
                scaleWidth = splintButtonRectTransform.sizeDelta.x,
                scaleHeight = splintButtonRectTransform.sizeDelta.y
            },

            ////leftControlScale = 1f, rightControlScale = 1f, punchControlScale = 1f, kickControlScale = 1f;
            leftControlScaleValue = ControlScaler.instance.leftControlScale,
            rightControlScaleValue = ControlScaler.instance.rightControlScale,
            kickControlScaleValue = ControlScaler.instance.kickControlScale,
            punchControlScaleValue = ControlScaler.instance.punchControlScale,

            GameplayVolume_value = VolumeSliderArray[0].value,
            UIVolume_value = VolumeSliderArray[1].value,
            MusicVolume_value = VolumeSliderArray[2].value,
            SFXVolume_value = VolumeSliderArray[3].value,


            audioVolumes = new string[]{
                (VolumeSliderValues[0]).text,
                (VolumeSliderValues[1]).text,
                (VolumeSliderValues[2]).text,
                (VolumeSliderValues[3]).text,
            }
        };

        SaveGameSettings(settings);
    }


    // public static GameSettings LoadSettings()
    GameSettings settings;
    void LoadSettings()
    {
        settings = LoadGameSettings();

        // Apply settings
    SetAnchoredPosition(leftControlRectTransform, settings.leftControl);
    SetAnchoredPosition(punchControlRectTransform, settings.punchControl);
    SetAnchoredPosition(kickControlRectTransform, settings.kickControl);

    SetAnchoredPosition(weaponPickupButtonRectTransform, settings.weaponPickupButton);
    SetAnchoredPosition(specialMoveButtonRectTransform, settings.specialMoveButton);
    SetAnchoredPosition(shieldButtonRectTransform, settings.shieldButton);
    SetAnchoredPosition(splintButtonRectTransform, settings.splintButton);

        VolumeSliderArray[0].value = settings.GameplayVolume_value;
        VolumeSliderArray[1].value = settings.UIVolume_value;
        VolumeSliderArray[2].value = settings.MusicVolume_value;
        VolumeSliderArray[3].value = settings.SFXVolume_value;

        (VolumeSliderValues[0]).text = settings.audioVolumes[0];
        (VolumeSliderValues[1]).text = settings.audioVolumes[1];
        (VolumeSliderValues[2]).text = settings.audioVolumes[2];
        (VolumeSliderValues[3]).text = settings.audioVolumes[3];
    }


    // Function to load position and size details for Controls
    public void SetAnchoredPosition(RectTransform rtTransform, ControlSettings controlsettings)
    {
        if (rtTransform == null || controlsettings == null) return;
        rtTransform.anchoredPosition = new Vector2(controlsettings.positionX, controlsettings.positionY);
        rtTransform.sizeDelta = new Vector2(controlsettings.scaleWidth, controlsettings.scaleHeight);
    }


    // Function that returns Original Scales of Controls
     // private (float, float) 
     //    leftControlSize = (1064.764f, 886.327f),
     //    blockControlSize = (596.32f, 160.784f),
     //    dodgeControlSize = (596.32f, 160.784f),
     //    rightControlSize = (1064.764f, 886.3271f),
     //    kickControlSize = (1064.764f, 886.3271f),
     //    punchControlSize = (1064.764f, 886.3271f);

    public static (float, float) OriginalScales(string rectReference){
        switch (rectReference){
            case "left_control":
                return (leftControlSize.Item1, leftControlSize.Item2);
                    // return (1550.608f, 1290.752f);

                case "weapon_pickup":
                return (weaponPickupButtonSize.Item1, weaponPickupButtonSize.Item2);

            case "special_move":
                return (specialMoveButtonSize.Item1, specialMoveButtonSize.Item2);

            case "shield":
                return (shieldButtonSize.Item1, shieldButtonSize.Item2);

            case "splint":
                return (splintButtonSize.Item1, splintButtonSize.Item2);

            case "kick":
                return (kickControlSize.Item1, kickControlSize.Item2);

            case "punch":
                return (punchControlSize.Item1, punchControlSize.Item2);

            default:
                return (0f, 0f);
        }

    }


    private static GameSettings ControlScaleGameSettings;
    public static (float, float) LoadedScale(string rectReference){
        ControlScaleGameSettings = LoadGameSettings();

        switch (rectReference){
            case "left_control":
                return (ControlScaleGameSettings.leftControl.scaleWidth, ControlScaleGameSettings.leftControl.scaleHeight);

            case "weapon_pickup":
                return (ControlScaleGameSettings.weaponPickupButton != null ? ControlScaleGameSettings.weaponPickupButton.scaleWidth : 0f,
                        ControlScaleGameSettings.weaponPickupButton != null ? ControlScaleGameSettings.weaponPickupButton.scaleHeight : 0f);

            case "special_move":
                return (ControlScaleGameSettings.specialMoveButton != null ? ControlScaleGameSettings.specialMoveButton.scaleWidth : 0f,
                        ControlScaleGameSettings.specialMoveButton != null ? ControlScaleGameSettings.specialMoveButton.scaleHeight : 0f);

            case "shield":
                return (ControlScaleGameSettings.shieldButton != null ? ControlScaleGameSettings.shieldButton.scaleWidth : 0f,
                        ControlScaleGameSettings.shieldButton != null ? ControlScaleGameSettings.shieldButton.scaleHeight : 0f);

            case "splint":
                return (ControlScaleGameSettings.splintButton != null ? ControlScaleGameSettings.splintButton.scaleWidth : 0f,
                        ControlScaleGameSettings.splintButton != null ? ControlScaleGameSettings.splintButton.scaleHeight : 0f);

            case "kick":
                return (ControlScaleGameSettings.kickControl.scaleWidth, ControlScaleGameSettings.kickControl.scaleHeight);

            case "punch":
                return (ControlScaleGameSettings.punchControl.scaleWidth, ControlScaleGameSettings.punchControl.scaleHeight);

            default:
                return (0f, 0f);
        }
    }


    // Default Position and Scale values
    private static (float, float) 
        leftControlPosition = (1012f, 836f),
        punchControlPosition = (-1046f, 1497f),
        kickControlPosition = (-651f, 856f),
        weaponPickupButtonPosition = (1500f, 500f),
        specialMoveButtonPosition = (1750f, 350f),
        shieldButtonPosition = (1250f, 350f),
        splintButtonPosition = (1000f, 350f);


    private static (float, float) 
        leftControlSize = (1236.143f, 1028.98f),
        punchControlSize = (786.249f, 654.485f),
        kickControlSize = (802.66f, 668.147f),
        weaponPickupButtonSize = (300f, 300f),
        specialMoveButtonSize = (300f, 300f),
        shieldButtonSize = (300f, 300f),
        splintButtonSize = (300f, 300f);


    // Function that contains default Control sizes
    void DefaultControlsSettings(){
        //Controls Position
        leftControlRectTransform.anchoredPosition = new Vector2(leftControlPosition.Item1, leftControlPosition.Item2);
        punchControlRectTransform.anchoredPosition = new Vector2(punchControlPosition.Item1, punchControlPosition.Item2);
        kickControlRectTransform.anchoredPosition = new Vector2(kickControlPosition.Item1, kickControlPosition.Item2);
        if (weaponPickupButtonRectTransform != null)
            weaponPickupButtonRectTransform.anchoredPosition = new Vector2(weaponPickupButtonPosition.Item1, weaponPickupButtonPosition.Item2);
        if (specialMoveButtonRectTransform != null)
            specialMoveButtonRectTransform.anchoredPosition = new Vector2(specialMoveButtonPosition.Item1, specialMoveButtonPosition.Item2);
        if (shieldButtonRectTransform != null)
            shieldButtonRectTransform.anchoredPosition = new Vector2(shieldButtonPosition.Item1, shieldButtonPosition.Item2);
        if (splintButtonRectTransform != null)
            splintButtonRectTransform.anchoredPosition = new Vector2(splintButtonPosition.Item1, splintButtonPosition.Item2);


        //Controls Scale, Width and Height
        leftControlRectTransform.sizeDelta = new Vector2(leftControlSize.Item1, leftControlSize.Item2);
        kickControlRectTransform.sizeDelta = new Vector2(kickControlSize.Item1, kickControlSize.Item2);
        punchControlRectTransform.sizeDelta = new Vector2(punchControlSize.Item1, punchControlSize.Item2);
        if (weaponPickupButtonRectTransform != null)
            weaponPickupButtonRectTransform.sizeDelta = new Vector2(weaponPickupButtonSize.Item1, weaponPickupButtonSize.Item2);
        if (specialMoveButtonRectTransform != null)
            specialMoveButtonRectTransform.sizeDelta = new Vector2(specialMoveButtonSize.Item1, specialMoveButtonSize.Item2);
        if (shieldButtonRectTransform != null)
            shieldButtonRectTransform.sizeDelta = new Vector2(shieldButtonSize.Item1, shieldButtonSize.Item2);
        if (splintButtonRectTransform != null)
            splintButtonRectTransform.sizeDelta = new Vector2(splintButtonSize.Item1, splintButtonSize.Item2);
    }



    // Function to Reset Control Settings, Linked to UI Reset button
    public void ResetControlSettings(){
        // Apply these values to the RectTransform of the UI element

        // Save the settings
        DefaultControlsSettings();
        SaveSettings();
        StartCoroutine(AnimatePopup("Reset Successful"));
    }


    // Function to Save Control Settings, Linked to UI Save button
    public void SaveControlSettings(){
        
        // Save the settings
        SaveSettings();
        StartCoroutine(AnimatePopup("Save Successful"));
    }


    // Function to show and hide GameObject
    IEnumerator AnimatePopup(string msg)
    {
        popup.SetActive(true);
        ((popup.transform.Find("text").gameObject).GetComponent<TextMeshProUGUI>()).text = msg;
        yield return new WaitForSeconds(1f);
        popup.SetActive(false);
    }



    //Saving and Loading Game Settings
    #region

        public static void SaveGameSettings(GameSettings settings){
            string json = JsonUtility.ToJson(settings);
            PlayerPrefs.SetString(GameSettingsKey, json);
            PlayerPrefs.Save();
        }

        public static GameSettings LoadGameSettings(){
            if (PlayerPrefs.HasKey(GameSettingsKey))
            {
                string json = PlayerPrefs.GetString(GameSettingsKey);
                return JsonUtility.FromJson<GameSettings>(json);
            }
            return new GameSettings(); // Return default settings if none are saved
        }

    #endregion
}



