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


public class MainStore_Menu : MonoBehaviour{
    public TextMeshProUGUI MenuSelection_text;
    public GameObject FirstShopMenuSelectedObject;
    public GameObject[] MainStoreMenu_ToggleGameObjects;

    public GameObject[] Originals_GameObjects; // Array to hold the list of GameObjects
    public GameObject[] Coins_GameObjects; // Array to hold the list of GameObjects
    public GameObject[] BattlePass_GameObjects; // Array to hold the list of GameObjects

    private GameObject[] combinedArray;

    private Button[] MainStoreMenu_buttons;
    private string currentActiveMenuItem;

    private Color whiteColor = new Color(1f, 1f, 1f); // Color for the currently selected GameObject
    private Color blue_selectedColor = new Color(0.4313726f, 0.6235294f, 0.9607843f);
    private Color normalColor = new Color(0.04705882f, 0.07058824f, 0.1215686f);

    void OnEnable(){

        // Initialize the array to store Button components
        MainStoreMenu_buttons = new Button[MainStoreMenu_ToggleGameObjects.Length];

        // Iterate over each GameObject in the array
        for (int i = 0; i < MainStoreMenu_ToggleGameObjects.Length; i++){
            // Get the Button component from the current GameObject
            Button button = MainStoreMenu_ToggleGameObjects[i].GetComponent<Button>();

            // Check if the Button component exists
            if (button != null)
            {
                // Store the Button component in the array
                MainStoreMenu_buttons[i] = button;
            }
            else
            {
                Debug.LogWarning("Button component not found on GameObject: " + MainStoreMenu_ToggleGameObjects[i].name);
            }
        }
        // MainStoreMenu_buttons = GetComponentsInChildren<Button>();
        EventSystem.current.SetSelectedGameObject(null);    //Clear previous selected gameobject
        EventSystem.current.SetSelectedGameObject(FirstShopMenuSelectedObject);
        Debug.LogWarning(FirstShopMenuSelectedObject.name);

        // Find all GameObjects with the tag "MainStore_MenuItem"
        // GameObject[] menuItems = GameObject.FindGameObjectsWithTag("MainStore_MenuItem");

        


        // Concatenate the arrays
        combinedArray = Originals_GameObjects.Concat(Coins_GameObjects).Concat(BattlePass_GameObjects).ToArray();

        // Set the active state of each GameObject to false
        foreach (GameObject menuItem in combinedArray){
            menuItem.SetActive(false);
        }

        foreach(GameObject menuItem in MainStoreMenu_ToggleGameObjects){
            setCaretDown(menuItem);
        }
    }


    void setCaretDown(GameObject currentGameObject){
        GameObject caretup_GO = (currentGameObject.transform.Find("caretUp")).gameObject;
        caretup_GO.SetActive(false);

        GameObject caretdown_GO = (currentGameObject.transform.Find("caretDown")).gameObject;
        // Debug.Log("CD = " + caretdown_GO.name);
        caretdown_GO.SetActive(true);

        setTabBG(false, currentGameObject);
    }

    void setCaretUp(GameObject currentGameObject){
        GameObject caretup_GO = (currentGameObject.transform.Find("caretUp")).gameObject;
        caretup_GO.SetActive(true);

        GameObject caretdown_GO = (currentGameObject.transform.Find("caretDown")).gameObject;
        caretdown_GO.SetActive(false);

        setTabBG(true, currentGameObject);
    }


    void setTabBG(bool tabBG_value, GameObject currentGameObject){
        // GameObject tabBG_GO = (currentGameObject.transform.Find("Tab_BG")).gameObject;
        // tabBG_GO.SetActive(tabBG_value);
    }


    // Method to handle button clicks
    void ClickHandler(Button clickedButton){

        // Determine which button is clicked
        if (clickedButton != null){
            GameObject selectedGameObject = clickedButton.gameObject;
            string buttonName = clickedButton.gameObject.name;
            // currentActiveMenuItem = clickedButton.gameObject.name;
            // Debug.Log("Btn Clicked = " + buttonName);
            // Debug.Log("SelectedGameObject = " + selectedGameObject);
            
            //Perform actions based on the button clicked
            switch (buttonName){
                case "Originals":
                    GoToSelectedMenuItemChild(Originals_GameObjects);
                    DeactiveMenuItems(Originals_GameObjects, selectedGameObject);
                    break;

                case "Coins":
                    GoToSelectedMenuItemChild(Coins_GameObjects);
                    DeactiveMenuItems(Coins_GameObjects, selectedGameObject);
                    ChangeContentToCurrentSelection("Coins");
                    break;

                case "BattlePass":
                    GoToSelectedMenuItemChild(BattlePass_GameObjects);
                    DeactiveMenuItems(BattlePass_GameObjects, selectedGameObject);
                    ChangeContentToCurrentSelection("BattlePass");
                    break;

                case "Maasai":
                    // GoToSelectedMenuItemChild(BattlePass_GameObjects);
                    // DeactiveMenuItems(BattlePass_GameObjects, selectedGameObject);
                    ChangeContentToCurrentSelection("Maasai1");
                    break;

                case "Maasai2":
                    // GoToSelectedMenuItemChild(BattlePass_GameObjects);
                    // DeactiveMenuItems(BattlePass_GameObjects, selectedGameObject);
                    ChangeContentToCurrentSelection("Maasai2");
                    break;
            }
        }
    }

    void ChangeContentToCurrentSelection(string selectionText){
        Debug.Log("XD = " + selectionText);
        MenuSelection_text.text = selectionText;
    }

    //When a Menu item is selected, go to its first child as selected
    void GoToSelectedMenuItemChild(GameObject[] selectedItemChild){
        EventSystem.current.SetSelectedGameObject(null);    //Clear previous selected gameobject
        EventSystem.current.SetSelectedGameObject(selectedItemChild[0]);
    }


    // private GameObject currentSelectedMenu_GameObject = null;
    //Deactivate all GameObject except those in ActivategameObject
    void DeactiveMenuItems(GameObject[] ActivegameObject, GameObject selectedGameObject){
        // Debug.Log("S = " + selectedGameObject.name);

        // CheckIfMenuItemIsActive(selectedGameObject);

        foreach(GameObject obj in combinedArray){
            // Check if the object is within BattlePass_GameObjects, which Array items to show
            bool isActiveGameObject_Present = System.Array.Exists(ActivegameObject, element => element == obj);

            //If in the selected item array 
            if (isActiveGameObject_Present){
                obj.SetActive(true);

            }else{  //If not in the selected item array
                obj.SetActive(false);
            }

            if (CheckIfMenuItemIsActive(selectedGameObject)){
                Debug.Log("Already Active");
                obj.SetActive(false);
            }
        }

        // currentSelectedMenu_GameObject = selectedGameObject;

        
        //Set the caret icon
        foreach(GameObject obj in MainStoreMenu_ToggleGameObjects){
            Debug.LogError(obj.name);
            if (selectedGameObject != null){
                if (obj == selectedGameObject){
                    if (CheckIfMenuItemIsActive(obj) == true){
                        Debug.LogError("A");
                        setCaretDown(selectedGameObject);
                    }else{

                    // if (CheckIfMenuItemIsActive(obj) == false){
                        Debug.LogError("N");
                        setCaretUp(selectedGameObject);
                    }
                }

                // if ((obj == selectedGameObject) && (CheckIfMenuItemIsActive(obj))){
                //     Debug.Log("Carat Already Active");
                //     setCaretDown(obj);
                // }

                // if ((obj == selectedGameObject) && !(CheckIfMenuItemIsActive(obj))){
                //     // Debug.Log("YUP");
                //     setCaretUp(selectedGameObject);
                // }

                if (obj != selectedGameObject){
                    // Debug.Log("NOPE");
                    setCaretDown(obj);       
                }
            }
        }
    }


    public bool CheckIfMenuItemIsActive(GameObject menuItem){
        GameObject caretup_GO = (menuItem.transform.Find("caretUp")).gameObject;

        //If Active
        if (caretup_GO.activeSelf){
            Debug.Log(menuItem.name + " Already Active");
            return true;
        }else{
            Debug.Log(menuItem.name + " Not Active");
            return false;
        }
    }


    // Start is called before the first frame update
    void Start(){
        foreach (Button button in MainStoreMenu_buttons){
            button.onClick.AddListener(() => ClickHandler(button));
        }    
    }


    void ChangeCurrentSelectedGameObject(GameObject selectedObject){
        // Find the child GameObject named "text" under the selectedObject
        Transform textTransform = selectedObject.transform.Find("text");
        // Transform imgTransform = selectedObject.transform.Find("img_icon");

        // //There is a text element child found
        if (textTransform != null){
            TextMeshProUGUI textMesh = textTransform.GetComponent<TextMeshProUGUI>();
            textMesh.fontSize = 145;
        }

        // if (imgTransform != null){
        //     RectTransform rectTransform = imgTransform.GetComponent<RectTransform>();   //Get the RectTransform component of the child GameObject
        //     rectTransform.sizeDelta = new Vector2(50, 50);  //Set the size of the RectTransform component
        // }
        
        // Debug.Log("Current = " + selectedObject.name);

        Image image = selectedObject.GetComponent<Image>(); //Get the Image component attached to the selected GameObject
        image.color = whiteColor;


        Button btn = selectedObject.GetComponent<Button>();
        ColorBlock colors = btn.colors;     //Get the colors structure of the button
        colors.normalColor = blue_selectedColor;    //Assign the selected color to the selected state
        btn.colors = colors;    //Assign the modified colors back to the button

    }


    private static GameObject lastSelectedObject = null;
    // Update is called once per frame
    void Update(){
        if ((EventSystem.current != null)){
            GameObject selectedObject = EventSystem.current.currentSelectedGameObject; // Get the currently selected GameObject
            // lastMenuSceneSelectedObject = selectedObject;
            Debug.Log("Sel = " + selectedObject.name);

            ChangeCurrentSelectedGameObject (selectedObject);


            // Check if the current selected GameObject is different from the last selected GameObject
            if ((selectedObject != lastSelectedObject) && (lastSelectedObject != null)){
                // Check if the GameObject has an Image component
                Image lastImage = lastSelectedObject.GetComponent<Image>();
                lastImage.color = normalColor;

                Button btn = lastSelectedObject.GetComponent<Button>();
                ColorBlock colors = btn.colors;     //Get the colors structure of the button
                colors.normalColor = whiteColor;    //Assign the selected color to the selected state
                btn.colors = colors;    //Assign the modified colors back to the button

                Transform textTransform2 = lastSelectedObject.transform.Find("text");
                // Transform imgTransform2 = lastSelectedObject.transform.Find("img_icon");
                if (textTransform2 != null){
                    TextMeshProUGUI textMesh = textTransform2.GetComponent<TextMeshProUGUI>();
                    textMesh.fontSize = 125;
                }

                // if (imgTransform2 != null){
                //     // Get the RectTransform component of the child GameObject
                //     RectTransform rectTransform = imgTransform2.GetComponent<RectTransform>();
                //     // Set the size of the RectTransform component
                //     rectTransform.sizeDelta = new Vector2(40, 40);
                // }

                // Update the reference to the last selected GameObject
                lastSelectedObject = selectedObject;
            }

            if (lastSelectedObject == null){
                lastSelectedObject = selectedObject;
            }
        }
        
    }
}
