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


// Class to represent character information
[System.Serializable]
public class CharacterInfo
{
    public string characterName;
    public string iconName;
    public string modelName;
    public int price;
    public string productID;
    public bool isUnlocked;
}


public class StoreManager : MonoBehaviour
{
    public Color selectedColor = new Color(0.953f, 0.811f, 0.180f); // Color for the selected button (converted from hexadecimal)
    public Color defaultColor = new Color(0.035f, 0.051f, 0.161f); // Default color for unselected buttons (converted from hexadecimal)

    public Color defaultSelectionBtn_Color = new Color(0.294f, 0.686f, 0.196f); // Default color for unselected buttons (converted from hexadecimal)
    public Color selectedSelectionBtn_Color = new Color(0.227f, 0.537f, 0.733f); // Default color for unselected buttons (converted from hexadecimal)

    public GameObject characterSelectionCanvas; // Reference to the Character_Selection canvas
    public GameObject characterIconPrefab; // Reference to the prefab for character icons

    [HideInInspector]
    public List<CharacterInfo> characterList; // List of character information

    // public GameObject characterSelectionCanvas; // Reference to the Character_Selection canvas
    // public GameObject topLeftContainerPrefab; // Reference to the prefab to be duplicated
    // public int numberOfDuplicates = 3; // Number of duplicates to create

    [SerializeField]
    private List<CharacterInfo> additionalCharacters;

    public GameObject buy_popUp;
    int buy_popUp_active = 0;

    // Start is called before the first frame update
    void Start()
    {
        // Debug.Log ("Hello B");
        GameObject buy_popUp = GameObject.Find("Buy_PopUp");

        if (buy_popUp != null){
            buy_popUp.SetActive(false);
        }


        // Initialize characterList with sample data
        characterList = new List<CharacterInfo>
        {
            new CharacterInfo { characterName = "CAT", iconName = "Cat4X-removebg-preview 2", modelName = "Cat4X-removebg-preview 2", price = 1300, productID = "com.ex.cat", isUnlocked = true },
            new CharacterInfo { characterName = "CHEETAH", iconName = "Cheetah5X-removebg-preview 2", modelName = "Cheetah5X-removebg-preview 2", price = 1500, productID = "com.ex.cheetah", isUnlocked = true },
            new CharacterInfo { characterName = "EAGLE", iconName = "EagleX-removebg-preview 2",modelName = "EagleX-removebg-preview 2", price = 2000, productID = "com.ex.eagle", isUnlocked = true },
            // Add more characters as needed
        };

        // Add characters from the Unity Inspector
        characterList.AddRange(additionalCharacters);

        PopulateShopWithCharacters();
    }

    //Add Items to the shop
    void PopulateShopWithCharacters()
    {
        // Debug.Log ("Hello B");
        // Check if the canvas and prefab are assigned
        if (characterSelectionCanvas == null)
        {
            // Debug.LogError("Character_Selection canvas is not assigned!");
            return;
        }

        if (characterIconPrefab == null)
        {
            // Debug.LogError("Character Icon prefab is not assigned!");
            return;
        }

        // Loop through the character list and create icons for each character
        foreach (CharacterInfo characterInfo in characterList)
        {
            // Instantiate the character icon prefab
            GameObject characterIcon = Instantiate(characterIconPrefab, characterSelectionCanvas.transform);

            // Access the Button component on the prefab
            Button iconButton = characterIcon.GetComponent<Button>();
            if (iconButton != null)
            {
                // Access the Image component on the Button and set the sprite (assuming your icon is a sprite)
                Image iconImage = iconButton.transform.Find("shop_item_image").GetComponent<Image>();
                if (iconImage != null)
                {
                    // Load the sprite based on the correct path
                    // string spritePath = "Faces/" + characterInfo.iconName;

                    // Load the sprite based on the correct path
                    string spritePath = characterInfo.isUnlocked ? "Characters/Faces/" + characterInfo.iconName : "Characters/Faces/lock";
                    // string currentDirectory = Environment.CurrentDirectory;
                    // Debug.Log (currentDirectory);

                    Sprite iconSprite = Resources.Load<Sprite>(spritePath);
                    iconImage.sprite = iconSprite;

                    if (iconSprite == null)
                    {
                        Debug.LogError($"Sprite not found at path: {spritePath}");
                    }

                    // Adjust the width and height if "lock" sprite is used
                    if (!characterInfo.isUnlocked)
                    {
                        iconImage.rectTransform.sizeDelta = new Vector2(600f, 500f);
                    }

                    // Add an onClick listener to the button
                    iconButton.onClick.AddListener(() => OnCharacterButtonClick(characterInfo));
                }

                // Access the Image component on the Button and set the sprite (assuming your icon is a sprite)
                TextMeshProUGUI item_price = iconButton.transform.Find("shop_item_price").GetComponent<TextMeshProUGUI>();

                if (item_price != null){
                    string char_price = $"{characterInfo.price}";
                    item_price.text = char_price;
                }
            }

            // Optionally, you can rename the instantiated character icon
            // characterIcon.name = characterInfo.characterName + "_Icon";
            characterIcon.name = characterInfo.productID + "_Icon";

            // Example: Output character information
            // Debug.Log($"Character: {characterInfo.characterName}, Price: {characterInfo.price}, Unlocked: {characterInfo.isUnlocked}");
        }

        // Disable the original prefab
        characterIconPrefab.SetActive(false);
    }


    // Method to be called when a character button is clicked
    void OnCharacterButtonClick(CharacterInfo characterInfo)
    {
        // // Display the character's name using Debug.Log
        Debug.Log($"Selected Character: {characterInfo.characterName}");
        activate_buyPopUp();
        buy_popUp.SetActive(true);

        // GameObject item_name_topgmo = GameObject.Find("item_image");
        // Debug.Log(item_name_topgmo);

        // //Buy Popup has been activated
        if (buy_popUp_active == 1){
            GameObject item_name_top_gmo = GameObject.Find("item_name_top");
            GameObject item_name_left_gmo = GameObject.Find("item_name_left");
            GameObject item_image_gmo = GameObject.Find("item_image");
            GameObject item_price_buy_gmo = GameObject.Find("item_price_buy");

            //Get item names (top and left)
            TextMeshProUGUI item_name_top_component = item_name_top_gmo.GetComponent<TextMeshProUGUI>();
            TextMeshProUGUI item_name_left_component = item_name_left_gmo.GetComponent<TextMeshProUGUI>();
            TextMeshProUGUI item_price_buy_gmo_component = item_price_buy_gmo.GetComponent<TextMeshProUGUI>();

            //Get item image
            Image item_image_component = item_image_gmo.GetComponent<Image>();

            item_name_top_component.text = characterInfo.characterName;
            item_name_left_component.text = characterInfo.characterName;
            item_price_buy_gmo_component.text = $"{characterInfo.price}";
            item_image_component.sprite = Resources.Load<Sprite>("Characters/Faces/" + characterInfo.iconName);

            //Buy button
            GameObject selectedCharacter_BuyBtn = GameObject.Find("item_purchase_btn");

            // Get the button component
            Button character_BuyBtn = selectedCharacter_BuyBtn.GetComponent<Button>();

            character_BuyBtn.onClick.RemoveAllListeners();
            character_BuyBtn.onClick.AddListener(() => BuyItemOnClick(characterInfo));
        }
    }

    // Function to handle the onClick event for BuyGold
    void BuyItemOnClick(CharacterInfo characterInfo)
    {
        // Find the GameObject named "InAppPurchasing"
        GameObject inAppPurchasing = GameObject.Find("InAppPurchasing");

        // Check if the GameObject is found
        if (inAppPurchasing != null)
        {
            // Get the StoreScript component attached to the "InAppPurchasing" GameObject
            StoreScript storeScript = inAppPurchasing.GetComponent<StoreScript>();

            // Check if the StoreScript component is found
            if (storeScript != null)
            {
                // Call the BuyGold function in the StoreScript
                Debug.Log($"Character: {characterInfo.characterName}, Price: {characterInfo.price}, Item ID: {characterInfo.productID}");
                storeScript.BuyGold(characterInfo.productID);
            }
            else
            {
                Debug.LogError("StoreScript component not found on the 'InAppPurchasing' GameObject.");
            }
        }
        else
        {
            Debug.LogError("GameObject with name 'InAppPurchasing' not found.");
        }
    }


    // Update is called once per frame
    void Update()
    {
        checkBuyPopUp_status();
    }

    void checkBuyPopUp_status(){
        if (buy_popUp_active == 1){
            buy_popUp.SetActive(true);
        }else{
            buy_popUp.SetActive(false);
        }
    }

    public void activate_buyPopUp(){
        // buy_popUp.SetActive(true); //
        buy_popUp_active = 1;
    }

    public void deactivate_buyPopUp(){
        // buy_popUp.SetActive(false); //
        buy_popUp_active = 0;
    }
}
