using UnityEngine;
using Firebase.Auth;
using Firebase.Database;
using System;
using Firebase.Extensions;
using System.Collections.Generic;
using Unity.VisualScripting;

public class GameManager : MonoBehaviour
{
    public bool Inventory_scene;
    public bool CharacterSelection_Scene;
    public int GameLevel = 1;
    public ItemOverview Overview;
    public Transform gridContainer; // Parent transform for the grid
    public GameObject itemPrefab; // Pr
    public string chestID;
    public string HelmetID;
    public string ShouldersID;
    public string GlovesID;
    public string LegsID;
    public string FeetID;

    private List<GameObject> itemModels = new List<GameObject>();
    public static GameManager Instance { get; private set; }
    private ItemType TypeToRemove;
    [Header(" Firebase variables")]
    public FirebaseAuth auth;
    public DatabaseReference reference;
    public string userId;
    private float spacing = 2.0f;
    // Inventory data
    public DataSnapshot inventorySnapshot;
    public DataSnapshot EquipmentSnapshot;
    // Events for manual and auto-refresh
    public event Action<DataSnapshot> OnInventoryDataChanged;
    private CharacterEquipmentCustomizer equipmentCustomizer;
    public Transform Chest_location;
    public Transform Helmet_location;
    public Transform Shoulders_location;
    public Transform Legs_location;
    public Transform gloves_location;
    public Transform Boots_location;
    [Header ("Models")]
    private ItemType lastSelectedArmorType;
    public  GameObject Chest_model;
    public GameObject helmet_model;
    public GameObject Shoulders_model;
    public GameObject Feet_model;
    public GameObject Legs_model;
    public GameObject Gloves_model;
    public class InventoryItemData
    {
        public ItemType ItemType;
        public string Name;
        public string Rarity;
        public string ArmorGrade;
        public ItemLockStatus LockStatus;
        public int ModelIndex;
        public int ItemLevel; // New property for item level
        public int Armor;
        public int MagicArmor;
        public int Health;
        public int Mana;
        public int Stamina;
        // Add other item properties as needed
    }
    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
            InitializeFirebase();
        }
        else
        {
            Destroy(gameObject);
        }
    }

    void InitializeFirebase()
    {
        auth = FirebaseAuth.DefaultInstance;
        reference = FirebaseDatabase.DefaultInstance.RootReference;
        userId = auth.CurrentUser.UserId;
      
            
        try
        {
            
            LoadInventory();
            GatherandPlaceEquipedd();
            
        }
        catch (Exception)
        {

            throw;
        }
           
        
        // Automatically load inventory data on start
     
        // Set up automatic data refresh (e.g., every minute)
        InvokeRepeating("AutoRefreshInventory", 0f, 60f);
    }
    private void Start()
    {
        equipmentCustomizer = FindObjectOfType<CharacterEquipmentCustomizer>();
        
    }

    private void RefreshUIForArmorType(ItemType armorType)
    {
        switch (armorType)
        {
            case ItemType.Chest:
                GatherAndPlaceItemModels_chest();
                break;
            case ItemType.Helmet:
                GatherAndPlaceItemModels_Helmet();
                break;
            case ItemType.Shoulders:
                GatherAndPlaceItemModels_Shoulders();
                break;
            case ItemType.Gloves:
                GatherAndPlaceItemModels_Gloves();
                break;
            case ItemType.Pants:
                GatherAndPlaceItemModels_Legs();
                break;
            case ItemType.Boots:
                GatherAndPlaceItemModels_boots();
                break;
            default:
                Debug.LogError($"Unknown armor type: {armorType}");
                break;
        }
    }

    public void UnequipArmor_Chest()
    {
        UnequipArmor(ItemType.Chest);
        if (lastSelectedArmorType == ItemType.Chest)
        {
            RefreshUIForArmorType(ItemType.Chest);
        }
    }
    public void UnequipArmor_Shoulders()
    {
        UnequipArmor(ItemType.Shoulders);
        if (lastSelectedArmorType == ItemType.Shoulders)
        {
            RefreshUIForArmorType(ItemType.Shoulders);
        }
    }
    public void UnequipArmor_Legs()
    {
        UnequipArmor(ItemType.Pants);
        if (lastSelectedArmorType == ItemType.Pants)
        {
            RefreshUIForArmorType(ItemType.Pants);
        }
    }
    public void UnequipArmor_Helmet()
    {
        UnequipArmor(ItemType.Helmet);
        if (lastSelectedArmorType == ItemType.Helmet)
        {
            RefreshUIForArmorType(ItemType.Helmet);
        }
    }
    public void UnequipArmor_Gloves()
    {
        UnequipArmor(ItemType.Gloves);
        if (lastSelectedArmorType == ItemType.Gloves)
        {
            RefreshUIForArmorType(ItemType.Gloves);
        }
    }
    public void UnequipArmor_Boots()
    {
        UnequipArmor(ItemType.Boots);
        if(lastSelectedArmorType == ItemType.Boots) { RefreshUIForArmorType(ItemType.Boots); }
       
    }
    public void UnequipArmor(ItemType itemType)
    {
        DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;
        userId = auth.CurrentUser.UserId;

        // Set the equipment type and ID based on the itemType
        string equipmentID = null;
        GameObject equipmentModel = null;

        switch (itemType)
        {
            case ItemType.Chest:
                equipmentID = chestID;
                equipmentModel = Chest_model;
                break;
            case ItemType.Helmet:
                equipmentID = HelmetID;
                equipmentModel = helmet_model;
                break;
            case ItemType.Shoulders:
                equipmentID = ShouldersID;
                equipmentModel = Shoulders_model;
                break;
            case ItemType.Gloves:
                equipmentID = GlovesID;
                equipmentModel = Gloves_model;
                break;
            case ItemType.Pants:
                equipmentID = LegsID;
                equipmentModel = Legs_model;
                break;
            case ItemType.Boots:
                equipmentID = FeetID;
                equipmentModel = Feet_model;
                break;
        }

        if (equipmentID == null || equipmentModel == null)
        {
            Debug.LogError($"Failed to unequip item. Invalid ItemType: {itemType}");
            return;
        }
        Destroy(equipmentModel);
        equipmentCustomizer.EquipArmor(itemType, 0);

        // Path to the equipped item in the "EquippedItems" node
        string equippedItemPath = $"users/{userId}/character/0/EquipedItems/{equipmentID}";
         equipmentID = null;
        // Retrieve the equipped item data
        reference.Child(equippedItemPath).GetValueAsync().ContinueWithOnMainThread(task =>
        {
            if (task.IsFaulted)
            {
                Debug.LogError($"Failed to load equipped item data at path {equippedItemPath}. Exception: {task.Exception}");
            }
            else if (task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;
                string equippedItemID = snapshot.Key;

                // Get the item data from the snapshot
                InventoryItemData equippedItemData = JsonUtility.FromJson<InventoryItemData>(snapshot.GetRawJsonValue());

                // Save the item data to the "inventory" node with a unique item ID
                string inventoryItemPath = $"users/{userId}/character/0/inventory/{equippedItemID}";
                reference.Child(inventoryItemPath).SetRawJsonValueAsync(snapshot.GetRawJsonValue()).ContinueWithOnMainThread(saveTask =>
                {
                    if (saveTask.IsFaulted)
                    {
                        Debug.LogError($"Failed to save unequipped item to inventory. Exception: {saveTask.Exception}");
                    }
                    else if (saveTask.IsCompleted)
                    {
                        Debug.Log("Item unequipped and saved to inventory successfully");

                        // Add the UI item back to the list
                       

                        // Load inventory after adding the item back to the list
                        LoadInventory();
                    }
                });

                // Remove the equipped item from the "EquippedItems" node
                reference.Child(equippedItemPath).RemoveValueAsync().ContinueWithOnMainThread(removeTask =>
                {
                    if (removeTask.IsFaulted)
                    {
                        Debug.LogError($"Failed to remove equipped item from EquippedItems. Exception: {removeTask.Exception}");
                    }
                    else if (removeTask.IsCompleted)
                    {
                        LoadInventory();
                        Debug.Log("Equipped item removed from EquippedItems successfully");
                         // Destroy the equipment model
                       
                    }
                });
            }
        });
    }
   

    public void LoadInventory()
    {
        reference.Child("users").Child(userId).Child("character").Child("0").Child("inventory").GetValueAsync().ContinueWithOnMainThread(task =>
        {
            if (task.IsFaulted)
            {
                Debug.LogError("Failed to load inventory: " + task.Exception);
            }
            else if (task.IsCompleted)
            {
                inventorySnapshot = task.Result;
                if (inventorySnapshot.Exists)
                {
                    Debug.Log("Inventory Loaded");
                    // Trigger the event when inventory data changes
                    OnInventoryDataChanged?.Invoke(inventorySnapshot);
                   if(lastSelectedArmorType == ItemType.Chest) { GatherAndPlaceItemModels_chest(); }
                     else if(lastSelectedArmorType == ItemType.Shoulders) { GatherAndPlaceItemModels_Shoulders(); }
                    else if (lastSelectedArmorType == ItemType.Helmet) { GatherAndPlaceItemModels_Helmet(); }
                    else if (lastSelectedArmorType == ItemType.Gloves) { GatherAndPlaceItemModels_Gloves(); }
                    else if (lastSelectedArmorType == ItemType.Pants) { GatherAndPlaceItemModels_Legs(); }
                    else if (lastSelectedArmorType == ItemType.Boots) { GatherAndPlaceItemModels_boots(); }
                    else { return; }
                }
                else
                {
                    Debug.Log("Inventory Empty");
                }
            }
        });
    }

    void AutoRefreshInventory()
    {

        LoadInventory();
        GatherandPlaceEquipedd();
    }

    public void GatherandPlaceEquipedd()
    {

        
        int TotalDef = 0;
        int TotalMagDef = 0;
        int HP = 0;
        int Stam = 0;
        int Mana = 0;
        DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;
        auth = FirebaseAuth.DefaultInstance;
        userId = auth.CurrentUser.UserId;
        Debug.Log("Loading Equiped");
        reference.Child("users").Child(userId).Child("character").Child("0").Child("EquipedItems").GetValueAsync().ContinueWithOnMainThread(task =>
        {
            if (task.IsFaulted)
            {
                Debug.LogError("Failed to load customization: " + task.Exception);
            }
            else if (task.IsCompleted)
            {
                EquipmentSnapshot = task.Result;

                if (EquipmentSnapshot.Exists)
                {
                    // Iterate through each child under "Inventory"
                    foreach (DataSnapshot itemSnapshot in EquipmentSnapshot.Children)
                    {
                        // Retrieve the item data from the snapshot
                        InventoryItemData data2 = JsonUtility.FromJson<InventoryItemData>(itemSnapshot.GetRawJsonValue());
                        TotalDef += data2.Armor;
                        TotalMagDef += data2.MagicArmor;
                        HP += data2.Health;
                        Stam += data2.Stamina;
                        Mana += data2.Mana;
                        if (data2.ItemType == ItemType.Chest)
                        {
                            RPGItem ownedItem = equipmentCustomizer.Chest[data2.ModelIndex];
                            equipmentCustomizer.currentChestIndex = data2.ModelIndex;
                            Debug.Log(data2.ModelIndex);
                            equipmentCustomizer.EquipArmor(ItemType.Chest, data2.ModelIndex);
                            chestID = itemSnapshot.Key;
                            if (Chest_model == null)
                            {
                                Chest_model = Instantiate(ownedItem.Model, Chest_location);
                            }
                            else if (helmet_model != null)
                            {
                                Destroy(Chest_model);
                                Chest_model = Instantiate(ownedItem.Model, Chest_location);
                            }
                        }
                        if (data2.ItemType == ItemType.Pants)
                        {
                            RPGItem ownedItem = equipmentCustomizer.Legs[data2.ModelIndex];         
                            equipmentCustomizer.currentLegsIndex = data2.ModelIndex;
                            Debug.Log(data2.ModelIndex);
                            equipmentCustomizer.EquipArmor(ItemType.Pants, data2.ModelIndex);
                            LegsID = itemSnapshot.Key;
                            if (Legs_model == null)
                            {
                                Legs_model = Instantiate(ownedItem.Model, Legs_location);
                            }
                            else if (helmet_model != null)
                            {
                                Destroy(Legs_model);
                                Legs_model = Instantiate(ownedItem.Model, Legs_location);
                            }



                        }
                        if (data2.ItemType == ItemType.Boots)
                        {
                            RPGItem ownedItem = equipmentCustomizer.Boots[data2.ModelIndex];
                            equipmentCustomizer.currentBootsIndex = data2.ModelIndex;
                            equipmentCustomizer.EquipArmor(ItemType.Boots, data2.ModelIndex);
                            FeetID = itemSnapshot.Key;
                            if (Feet_model == null)
                            {
                                Feet_model = Instantiate(ownedItem.Model, Boots_location);
                            }
                            else if (Feet_model != null)
                            {
                                Destroy(Feet_model);
                                Feet_model = Instantiate(ownedItem.Model, Boots_location);
                            }


                        }
                        if (data2.ItemType == ItemType.Shoulders)
                        {
                            RPGItem ownedItem = equipmentCustomizer.Shoulders[data2.ModelIndex];
                            equipmentCustomizer.currentShoulderIndex = data2.ModelIndex;
                            equipmentCustomizer.EquipArmor(ItemType.Shoulders, data2.ModelIndex);
                            ShouldersID = itemSnapshot.Key;
                            if (Shoulders_model == null)
                            {
                                Shoulders_model = Instantiate(ownedItem.Model, Shoulders_location);
                            }
                            else if (Feet_model != null)
                            {
                                Destroy(Shoulders_model);
                                Shoulders_model = Instantiate(ownedItem.Model, Shoulders_location);
                            }


                        }
                        if (data2.ItemType == ItemType.Helmet)
                        {
                            RPGItem ownedItem = equipmentCustomizer.Helmets[data2.ModelIndex];                       
                            equipmentCustomizer.currentHelmetIndex = data2.ModelIndex;
                            equipmentCustomizer.EquipArmor(ItemType.Helmet, data2.ModelIndex);
                            HelmetID = itemSnapshot.Key;
                            if (helmet_model == null)
                            {
                                helmet_model = Instantiate(ownedItem.Model, Helmet_location);
                            }
                            else if (helmet_model != null)
                            {
                                Destroy(helmet_model);
                                helmet_model = Instantiate(ownedItem.Model, Helmet_location);
                            }

                        }
                        if (data2.ItemType == ItemType.Gloves)
                        {
                            RPGItem ownedItem = equipmentCustomizer.Gloves[data2.ModelIndex];
                            equipmentCustomizer.EquipArmor(ItemType.Gloves, data2.ModelIndex);
                            GlovesID = itemSnapshot.Key;
                            if (Gloves_model == null)
                            {
                                Gloves_model = Instantiate(ownedItem.Model, gloves_location);
                            }
                            else if (Gloves_model != null)
                            {
                                Destroy(Gloves_model);
                                Gloves_model = Instantiate(ownedItem.Model, gloves_location);
                            }

                        }

                    }
                    Debug.Log($"Total Def: {TotalDef}");
                   // equipmentCustomizer.TotalCon = totalConstitution;
                    Debug.Log($"Total MagDef: {TotalMagDef}");
                 //   equipmentCustomizer.TotalStr = totalStrength;
                    Debug.Log($"Total HP: {HP}");
                 //   equipmentCustomizer.TotalInt = totalStrength;
                    Debug.Log($"Total Stamina: {Stam}");
                 //   equipmentCustomizer.TotalVit = totalStrength;
                    Debug.Log($"Total Mana: {Mana}");
                    equipmentCustomizer.SaveCustomization();

                }
                else
                {
                    Debug.Log("Equiped Empty");
                }
            }
        });

    }
    public void GatherAndPlaceItemModels_chest()
    {
        lastSelectedArmorType = ItemType.Chest;
        ClearItemModels();
        Debug.Log("REFRESHIGNG INVENTORY");
        // Get the unlocked items from the equipment customizer
        if (inventorySnapshot.Exists)
        {
            // Iterate through each child under "Inventory"
            foreach (DataSnapshot itemSnapshot in inventorySnapshot.Children)
            {
                // Retrieve the item data from the snapshot
                InventoryItemData data = JsonUtility.FromJson<InventoryItemData>(itemSnapshot.GetRawJsonValue());
                Debug.Log(itemSnapshot.GetRawJsonValue());

                if (data.ItemType == ItemType.Chest)
                {
                    RPGItem ownedItem = equipmentCustomizer.Chest[data.ModelIndex];
                    Debug.Log("We Got Chest");
                    GameObject model = Instantiate(ownedItem.Model, gridContainer);
                    ItemType type = ownedItem.itemType;
                    int armorIndex = ownedItem.itemIndex;
                    int addonIndex = ownedItem.SleevesIndex;
                    int LoweraddonIndex = ownedItem.lowerSleevesIndex;
                    string itemName = data.Name; // Get the item name
                    string equippedItemPath = $"users/{userId}/character/0/inventory/{itemSnapshot.Key}";
                    string _Pathname = itemSnapshot.Key;
                    int Armor = data.Armor;
                    string Rarity = data.Rarity;
                    int MagArmor = data.MagicArmor;
                    int Health = data.Health;
                    int stamina = data.Stamina;
                    int Mana = data.Mana;
                    int Level = data.ItemLevel;


                    Debug.Log(equipmentCustomizer);
                    if (model != null)
                    {
                        // Scale down the 3D model
                        model.transform.localScale = new Vector3(0.09f, 0.09f, 0.09f);

                        // Rotate the 3D model 180 degrees around the Y-axis
                        model.transform.Rotate(0.0f, 180.0f, 0.0f);

                        // Create a UI item
                        GameObject uiItem = Instantiate(itemPrefab, gridContainer);
                        uiItem.GetComponent<ArmorInventoryPrefab>().Model = model;
                        // Pass the item name and equipped item path to SetupArmorItem
                        uiItem.GetComponent<ArmorInventoryPrefab>().SetupArmorItem(type, armorIndex, addonIndex, LoweraddonIndex, itemName, equippedItemPath, _Pathname, Armor, MagArmor, Health, stamina, Mana, Rarity, Level);
                        // Set the position of the UI item in the grid
                        RectTransform rectTransform = uiItem.GetComponent<RectTransform>();
                        rectTransform.anchoredPosition = new Vector2(spacing * itemModels.Count, 0.0f);

                        // Set the 3D model as a child of the UI item
                        model.transform.SetParent(uiItem.transform, false);

                        // Display the stats text


                        // Add the UI item to the list for potential later use
                        itemModels.Add(uiItem);
                    }
                }
                // Now, 'data' contains the information of each item in the "Inventory" node
                // You can process this data as needed
            }
        }
        else
        {
            Debug.Log("Inventory Empty");
        }
    }
    public void GatherAndPlaceItemModels_Legs()
    {
         lastSelectedArmorType = ItemType.Pants;
        ClearItemModels();
        Debug.Log("REFRESHIGNG INVENTORY");
        // Get the unlocked items from the equipment customizer
        if (inventorySnapshot.Exists)
        {
            // Iterate through each child under "Inventory"
            foreach (DataSnapshot itemSnapshot in inventorySnapshot.Children)
            {
                // Retrieve the item data from the snapshot
                InventoryItemData data = JsonUtility.FromJson<InventoryItemData>(itemSnapshot.GetRawJsonValue());
                Debug.Log(itemSnapshot.GetRawJsonValue());

                if (data.ItemType == ItemType.Pants)
                {
                    RPGItem ownedItem = equipmentCustomizer.Legs[data.ModelIndex];
                    Debug.Log("We Got Chest");
                    GameObject model = Instantiate(ownedItem.Model, gridContainer);
                    ItemType type = ownedItem.itemType;
                    int armorIndex = ownedItem.itemIndex;
                    int addonIndex = ownedItem.SleevesIndex;
                    int LoweraddonIndex = ownedItem.lowerSleevesIndex;
                    string itemName = data.Name; // Get the item name
                    string equippedItemPath = $"users/{userId}/character/0/inventory/{itemSnapshot.Key}";
                    string _Pathname = itemSnapshot.Key;
                    int Armor = data.Armor;
                    string Rarity = data.Rarity;
                    int MagArmor = data.MagicArmor;
                    int Health = data.Health;
                    int stamina = data.Stamina;
                    int Mana = data.Mana;
                    int Level = data.ItemLevel;

                    Debug.Log(equipmentCustomizer);
                    if (model != null)
                    {
                        // Scale down the 3D model
                        model.transform.localScale = new Vector3(0.09f, 0.09f, 0.09f);

                        // Rotate the 3D model 180 degrees around the Y-axis
                        model.transform.Rotate(0.0f, 180.0f, 0.0f);

                        // Create a UI item
                        GameObject uiItem = Instantiate(itemPrefab, gridContainer);
                        uiItem.GetComponent<ArmorInventoryPrefab>().Model = model;
                        // Pass the item name and equipped item path to SetupArmorItem
                        uiItem.GetComponent<ArmorInventoryPrefab>().SetupArmorItem(type, armorIndex, addonIndex, LoweraddonIndex, itemName, equippedItemPath, _Pathname, Armor, MagArmor, Health, stamina, Mana, Rarity, Level);
                        // Set the position of the UI item in the grid
                        RectTransform rectTransform = uiItem.GetComponent<RectTransform>();
                        rectTransform.anchoredPosition = new Vector2(spacing * itemModels.Count, 0.0f);

                        // Set the 3D model as a child of the UI item
                        model.transform.SetParent(uiItem.transform, false);

                        // Display the stats text


                        // Add the UI item to the list for potential later use
                        itemModels.Add(uiItem);
                    }
                }
                // Now, 'data' contains the information of each item in the "Inventory" node
                // You can process this data as needed
            }
        }
        else
        {
            Debug.Log("Inventory Empty");
        }
    }
    public void GatherAndPlaceItemModels_Shoulders()
    {
        lastSelectedArmorType = ItemType.Shoulders;
        ClearItemModels();
        Debug.Log("REFRESHIGNG INVENTORY");
        // Get the unlocked items from the equipment customizer
        if (inventorySnapshot.Exists)
        {
            // Iterate through each child under "Inventory"
            foreach (DataSnapshot itemSnapshot in inventorySnapshot.Children)
            {
                // Retrieve the item data from the snapshot
                InventoryItemData data = JsonUtility.FromJson<InventoryItemData>(itemSnapshot.GetRawJsonValue());
               

                if (data.ItemType == ItemType.Shoulders)
                {
                    RPGItem ownedItem = equipmentCustomizer.Shoulders[data.ModelIndex];
                    Debug.Log("We Got Chest");
                    GameObject model = Instantiate(ownedItem.Model, gridContainer);
                    ItemType type = ownedItem.itemType;
                    int armorIndex = ownedItem.itemIndex;
                    int addonIndex = ownedItem.SleevesIndex;
                    int LoweraddonIndex = ownedItem.lowerSleevesIndex;
                    string itemName = data.Name; // Get the item name
                    string equippedItemPath = $"users/{userId}/character/0/inventory/{itemSnapshot.Key}";
                    string _Pathname = itemSnapshot.Key;
                    int Armor = data.Armor;
                    string Rarity = data.Rarity;
                    int MagArmor = data.MagicArmor;
                    int Health = data.Health;
                    int stamina = data.Stamina;
                    int Mana = data.Mana;
                    int Level = data.ItemLevel;

                   
                    if (model != null)
                    {
                        // Scale down the 3D model
                        model.transform.localScale = new Vector3(0.09f, 0.09f, 0.09f);

                        // Rotate the 3D model 180 degrees around the Y-axis
                        model.transform.Rotate(0.0f, 180.0f, 0.0f);

                        // Create a UI item
                        GameObject uiItem = Instantiate(itemPrefab, gridContainer);

                        // Pass the item name and equipped item path to SetupArmorItem
                        uiItem.GetComponent<ArmorInventoryPrefab>().SetupArmorItem(type, armorIndex, addonIndex, LoweraddonIndex, itemName, equippedItemPath, _Pathname, Armor, MagArmor, Health, stamina, Mana, Rarity, Level); uiItem.GetComponent<ArmorInventoryPrefab>().Model = model;
                        // Set the position of the UI item in the grid
                        RectTransform rectTransform = uiItem.GetComponent<RectTransform>();
                        rectTransform.anchoredPosition = new Vector2(spacing * itemModels.Count, 0.0f);

                        // Set the 3D model as a child of the UI item
                        model.transform.SetParent(uiItem.transform, false);

                        // Display the stats text


                        // Add the UI item to the list for potential later use
                        itemModels.Add(uiItem);
                    }
                }
                // Now, 'data' contains the information of each item in the "Inventory" node
                // You can process this data as needed
            }
        }
        else
        {
            Debug.Log("Inventory Empty");
        }
    }
    public void GatherAndPlaceItemModels_Helmet()
    {
        lastSelectedArmorType = ItemType.Helmet;
        ClearItemModels();
        Debug.Log("REFRESHIGNG INVENTORY");
        // Get the unlocked items from the equipment customizer
        if (inventorySnapshot.Exists)
        {
            // Iterate through each child under "Inventory"
            foreach (DataSnapshot itemSnapshot in inventorySnapshot.Children)
            {
                // Retrieve the item data from the snapshot
                InventoryItemData data = JsonUtility.FromJson<InventoryItemData>(itemSnapshot.GetRawJsonValue());
                

                if (data.ItemType == ItemType.Helmet)
                {
                    RPGItem ownedItem = equipmentCustomizer.Helmets[data.ModelIndex];
                    Debug.Log("We Got Chest");
                    GameObject model = Instantiate(ownedItem.Model, gridContainer);
                    ItemType type = ownedItem.itemType;
                    int armorIndex = ownedItem.itemIndex;
                    int addonIndex = ownedItem.SleevesIndex;
                    int LoweraddonIndex = ownedItem.lowerSleevesIndex;
                    string itemName = data.Name; // Get the item name
                    string equippedItemPath = $"users/{userId}/character/0/inventory/{itemSnapshot.Key}";
                    string _Pathname = itemSnapshot.Key;
                    int Armor = data.Armor;
                    string Rarity = data.Rarity;
                    int MagArmor = data.MagicArmor;
                    int Health = data.Health;
                    int stamina = data.Stamina;
                    int Mana = data.Mana;
                    int Level = data.ItemLevel;

                   
                    if (model != null)
                    {
                        // Scale down the 3D model
                        model.transform.localScale = new Vector3(0.09f, 0.09f, 0.09f);

                        // Rotate the 3D model 180 degrees around the Y-axis
                        model.transform.Rotate(0.0f, 180.0f, 0.0f);

                        // Create a UI item
                        GameObject uiItem = Instantiate(itemPrefab, gridContainer);

                        // Pass the item name and equipped item path to SetupArmorItem
                        uiItem.GetComponent<ArmorInventoryPrefab>().SetupArmorItem(type, armorIndex, addonIndex, LoweraddonIndex, itemName, equippedItemPath, _Pathname, Armor, MagArmor, Health, stamina, Mana, Rarity, Level);
                        uiItem.GetComponent<ArmorInventoryPrefab>().Model = model;
                        // Set the position of the UI item in the grid
                        RectTransform rectTransform = uiItem.GetComponent<RectTransform>();
                        rectTransform.anchoredPosition = new Vector2(spacing * itemModels.Count, 0.0f);

                        // Set the 3D model as a child of the UI item
                        model.transform.SetParent(uiItem.transform, false);

                        // Display the stats text


                        // Add the UI item to the list for potential later use
                        itemModels.Add(uiItem);
                    }
                }
                // Now, 'data' contains the information of each item in the "Inventory" node
                // You can process this data as needed
            }
        }
        else
        {
            Debug.Log("Inventory Empty");
        }
    }
    public void GatherAndPlaceItemModels_Gloves()
    {
        lastSelectedArmorType = ItemType.Gloves;
        ClearItemModels();
        Debug.Log("REFRESHIGNG INVENTORY");
        // Get the unlocked items from the equipment customizer
        if (inventorySnapshot.Exists)
        {
            // Iterate through each child under "Inventory"
            foreach (DataSnapshot itemSnapshot in inventorySnapshot.Children)
            {
                // Retrieve the item data from the snapshot
                InventoryItemData data = JsonUtility.FromJson<InventoryItemData>(itemSnapshot.GetRawJsonValue());
                

                if (data.ItemType == ItemType.Gloves)
                {
                    RPGItem ownedItem = equipmentCustomizer.Gloves[data.ModelIndex];
                    Debug.Log("We Got Chest");
                    GameObject model = Instantiate(ownedItem.Model, gridContainer);
                    ItemType type = ownedItem.itemType;
                    int armorIndex = ownedItem.itemIndex;
                    int addonIndex = ownedItem.SleevesIndex;
                    int LoweraddonIndex = ownedItem.lowerSleevesIndex;
                    string itemName = data.Name; // Get the item name
                    string equippedItemPath = $"users/{userId}/character/0/inventory/{itemSnapshot.Key}";
                    string _Pathname = itemSnapshot.Key;
                    int Armor = data.Armor;
                    string Rarity = data.Rarity;
                    int MagArmor = data.MagicArmor;
                    int Health = data.Health;
                    int stamina = data.Stamina;
                    int Mana = data.Mana;
                    int Level = data.ItemLevel;

                    
                    if (model != null)
                    {
                        // Scale down the 3D model
                        model.transform.localScale = new Vector3(0.09f, 0.09f, 0.09f);

                        // Rotate the 3D model 180 degrees around the Y-axis
                        model.transform.Rotate(0.0f, 180.0f, 0.0f);

                        // Create a UI item
                        GameObject uiItem = Instantiate(itemPrefab, gridContainer);

                        // Pass the item name and equipped item path to SetupArmorItem
                        uiItem.GetComponent<ArmorInventoryPrefab>().SetupArmorItem(type, armorIndex, addonIndex, LoweraddonIndex, itemName, equippedItemPath, _Pathname, Armor, MagArmor, Health, stamina, Mana, Rarity, Level);
                        uiItem.GetComponent<ArmorInventoryPrefab>().Model = model;
                        // Set the position of the UI item in the grid
                        RectTransform rectTransform = uiItem.GetComponent<RectTransform>();
                        rectTransform.anchoredPosition = new Vector2(spacing * itemModels.Count, 0.0f);

                        // Set the 3D model as a child of the UI item
                        model.transform.SetParent(uiItem.transform, false);

                        // Display the stats text


                        // Add the UI item to the list for potential later use
                        itemModels.Add(uiItem);
                    }
                }
                // Now, 'data' contains the information of each item in the "Inventory" node
                // You can process this data as needed
            }
        }
        else
        {
            Debug.Log("Inventory Empty");
        }
    }
    public void GatherAndPlaceItemModels_boots()
    {
        lastSelectedArmorType = ItemType.Boots;
        ClearItemModels();
        Debug.Log("REFRESHIGNG INVENTORY");
        // Get the unlocked items from the equipment customizer
        if (inventorySnapshot.Exists)
        {
            // Iterate through each child under "Inventory"
            foreach (DataSnapshot itemSnapshot in inventorySnapshot.Children)
            {
                // Retrieve the item data from the snapshot
                InventoryItemData data = JsonUtility.FromJson<InventoryItemData>(itemSnapshot.GetRawJsonValue());
              

                if (data.ItemType == ItemType.Boots)
                {
                    RPGItem ownedItem = equipmentCustomizer.Boots[data.ModelIndex];
                   
                    GameObject model = Instantiate(ownedItem.Model, gridContainer);
                    ItemType type = ownedItem.itemType;
                    int armorIndex = ownedItem.itemIndex;
                    int addonIndex = ownedItem.SleevesIndex;
                    int LoweraddonIndex = ownedItem.lowerSleevesIndex;
                    string itemName = data.Name; // Get the item name
                    string equippedItemPath = $"users/{userId}/character/0/inventory/{itemSnapshot.Key}";
                    string _Pathname = itemSnapshot.Key;
                    int Armor = data.Armor;
                    string Rarity = data.Rarity;
                    int MagArmor = data.MagicArmor;
                    int Health = data.Health;
                    int stamina = data.Stamina;
                    int Mana = data.Mana;
                    int Level = data.ItemLevel;
                    Debug.Log(equipmentCustomizer);
                    if (model != null)
                    {
                        // Scale down the 3D model
                        model.transform.localScale = new Vector3(0.09f, 0.09f, 0.09f);

                        // Rotate the 3D model 180 degrees around the Y-axis
                        model.transform.Rotate(0.0f, 180.0f, 0.0f);

                        // Create a UI item
                        GameObject uiItem = Instantiate(itemPrefab, gridContainer);

                        // Pass the item name and equipped item path to SetupArmorItem
                        uiItem.GetComponent<ArmorInventoryPrefab>().SetupArmorItem(type, armorIndex, addonIndex, LoweraddonIndex, itemName, equippedItemPath, _Pathname, Armor, MagArmor, Health, stamina, Mana, Rarity, Level); uiItem.GetComponent<ArmorInventoryPrefab>().Model = model;
                        // Set the position of the UI item in the grid
                        RectTransform rectTransform = uiItem.GetComponent<RectTransform>();
                        rectTransform.anchoredPosition = new Vector2(spacing * itemModels.Count, 0.0f);

                        // Set the 3D model as a child of the UI item
                        model.transform.SetParent(uiItem.transform, false);

                        // Display the stats text


                        // Add the UI item to the list for potential later use
                        itemModels.Add(uiItem);
                    }
                }
                // Now, 'data' contains the information of each item in the "Inventory" node
                // You can process this data as needed
            }
        }
        else
        {
            Debug.Log("Inventory Empty");
        }
    }
    void ClearItemModels()
    {
        foreach (GameObject uiItem in itemModels)
        {
            Destroy(uiItem);
        }

        itemModels.Clear();
    }

}