using UnityEngine;
using UnityEngine.UIElements;
using System.Collections.Generic;

[System.Serializable]
public class TownSetupHelper : MonoBehaviour
{
    [Header("Auto-Setup Configuration")]
    public bool createSampleShops = true;
    public bool loadSampleItems = true;

    [Header("Generated Shops")]
    public TownShop weaponShop;
    public TownShop armorShop;
    public TownShop potionShop;
    public TownShop generalStore;

    [ContextMenu("Setup Sample Town")]
    public void SetupSampleTown()
    {
        if (createSampleShops)
        {
            CreateShopGameObjects();
        }

        if (loadSampleItems)
        {
            LoadSampleItemsToShops();
        }

        Debug.Log("Sample town setup complete!");
    }

    private void CreateShopGameObjects()
    {
        // Create Weapon Shop
        if (weaponShop == null)
        {
            var weaponShopGO = new GameObject("WeaponShop");
            weaponShopGO.transform.SetParent(transform);
            weaponShop = weaponShopGO.AddComponent<TownShop>();
            ConfigureWeaponShop();
        }

        // Create Armor Shop
        if (armorShop == null)
        {
            var armorShopGO = new GameObject("ArmorShop");
            armorShopGO.transform.SetParent(transform);
            armorShop = armorShopGO.AddComponent<TownShop>();
            ConfigureArmorShop();
        }

        // Create Potion Shop
        if (potionShop == null)
        {
            var potionShopGO = new GameObject("PotionShop");
            potionShopGO.transform.SetParent(transform);
            potionShop = potionShopGO.AddComponent<TownShop>();
            ConfigurePotionShop();
        }

        // Create General Store
        if (generalStore == null)
        {
            var generalStoreGO = new GameObject("GeneralStore");
            generalStoreGO.transform.SetParent(transform);
            generalStore = generalStoreGO.AddComponent<TownShop>();
            ConfigureGeneralStore();
        }
    }

    private void ConfigureWeaponShop()
    {
        weaponShop.buildingName = "The Forge";
        weaponShop.shopType = ShopType.Weapons;
        weaponShop.shopkeeperName = "Gareth the Smith";
        weaponShop.profitMargin = 1.3f; // 30% markup
        weaponShop.sellbackRate = 0.6f; // 60% when selling back
        weaponShop.description = "Fine weapons crafted by the town's master smith";
        weaponShop.isInteractable = true;
        weaponShop.buildingColor = new Color(0.8f, 0.2f, 0.2f); // Red
    }

    private void ConfigureArmorShop()
    {
        armorShop.buildingName = "Ironclad Armory";
        armorShop.shopType = ShopType.Armor;
        armorShop.shopkeeperName = "Miranda the Armorer";
        armorShop.profitMargin = 1.25f; // 25% markup
        armorShop.sellbackRate = 0.6f;
        armorShop.description = "Protective gear for the discerning adventurer";
        armorShop.isInteractable = true;
        armorShop.buildingColor = new Color(0.2f, 0.2f, 0.8f); // Blue
    }

    private void ConfigurePotionShop()
    {
        potionShop.buildingName = "The Bubbling Cauldron";
        potionShop.shopType = ShopType.Potions;
        potionShop.shopkeeperName = "Elias the Alchemist";
        potionShop.profitMargin = 1.4f; // 40% markup (potions are specialized)
        potionShop.sellbackRate = 0.5f; // Lower sellback for consumables
        potionShop.description = "Magical elixirs and healing draughts";
        potionShop.isInteractable = true;
        potionShop.buildingColor = new Color(0.2f, 0.8f, 0.2f); // Green
    }

    private void ConfigureGeneralStore()
    {
        generalStore.buildingName = "Pete's General Goods";
        generalStore.shopType = ShopType.General;
        generalStore.shopkeeperName = "Old Pete";
        generalStore.profitMargin = 1.2f; // 20% markup
        generalStore.sellbackRate = 0.65f; // Better sellback for general goods
        generalStore.description = "Everything an adventurer needs, and some things they don't";
        generalStore.isInteractable = true;
        generalStore.buildingColor = new Color(1f, 0.65f, 0f); // Orange
    }

    private void LoadSampleItemsToShops()
    {
        // Load all items from Resources
        var allWeapons = Resources.LoadAll<WeaponItem>("Items/Weapons");
        var allArmor = Resources.LoadAll<ArmorItem>("Items/Armor");
        var allMisc = Resources.LoadAll<MiscellaneousItem>("Items/Miscellaneous");

        Debug.Log($"Loaded {allWeapons.Length} weapons, {allArmor.Length} armor pieces, {allMisc.Length} misc items");

        // Add weapons to weapon shop
        if (weaponShop != null)
        {
            weaponShop.baseInventory.Clear();
            foreach (var weapon in allWeapons)
            {
                if (weapon != null)
                    weaponShop.baseInventory.Add(weapon);
            }
            Debug.Log($"Added {allWeapons.Length} weapons to weapon shop");
        }

        // Add armor to armor shop
        if (armorShop != null)
        {
            armorShop.baseInventory.Clear();
            foreach (var armor in allArmor)
            {
                if (armor != null)
                    armorShop.baseInventory.Add(armor);
            }
            Debug.Log($"Added {allArmor.Length} armor pieces to armor shop");
        }

        // Add consumables to potion shop
        if (potionShop != null)
        {
            potionShop.baseInventory.Clear();
            foreach (var misc in allMisc)
            {
                if (misc != null && misc.itemType == ItemType.Consumable)
                    potionShop.baseInventory.Add(misc);
            }
            Debug.Log($"Added consumables to potion shop");
        }

        // Add everything to general store (smaller selection)
        if (generalStore != null)
        {
            generalStore.baseInventory.Clear();

            // Add a few basic weapons
            for (int i = 0; i < Mathf.Min(3, allWeapons.Length); i++)
            {
                if (allWeapons[i] != null)
                    generalStore.baseInventory.Add(allWeapons[i]);
            }

            // Add a few basic armor pieces
            for (int i = 0; i < Mathf.Min(3, allArmor.Length); i++)
            {
                if (allArmor[i] != null)
                    generalStore.baseInventory.Add(allArmor[i]);
            }

            // Add misc items
            foreach (var misc in allMisc)
            {
                if (misc != null && misc.itemType != ItemType.Consumable)
                    generalStore.baseInventory.Add(misc);
            }

            Debug.Log($"Added mixed items to general store");
        }
    }

    [ContextMenu("Create Test Items")]
    public void CreateTestItems()
    {
        CreateTestWeapons();
        CreateTestArmor();
        CreateTestConsumables();
        CreateTestMiscItems();
    }

    private void CreateTestWeapons()
    {
        // This would create ScriptableObject assets - but that requires editor scripts
        // For now, just log what would be created
        Debug.Log("Test weapons that should be created:");
        Debug.Log("- Simple Sword (15g) - Basic iron blade");
        Debug.Log("- War Axe (22g) - Heavy two-handed axe");
        Debug.Log("- Hunting Bow (18g) - Reliable ranged weapon");
        Debug.Log("- Iron Dagger (8g) - Quick and light");
        Debug.Log("- Wooden Staff (12g) - For spellcasters");
    }

    private void CreateTestArmor()
    {
        Debug.Log("Test armor that should be created:");
        Debug.Log("- Leather Vest (10g) - Light chest protection");
        Debug.Log("- Iron Helmet (15g) - Sturdy head protection");
        Debug.Log("- Chainmail Shirt (35g) - Medium protection");
        Debug.Log("- Leather Boots (6g) - Basic foot protection");
        Debug.Log("- Iron Gauntlets (12g) - Hand protection");
    }

    private void CreateTestConsumables()
    {
        Debug.Log("Test consumables that should be created:");
        Debug.Log("- Health Potion (5g) - Restores 25 HP");
        Debug.Log("- Mana Potion (7g) - Restores 15 MP");
        Debug.Log("- Antidote (3g) - Cures poison");
        Debug.Log("- Stamina Elixir (4g) - Restores energy");
    }

    private void CreateTestMiscItems()
    {
        Debug.Log("Test misc items that should be created:");
        Debug.Log("- Hemp Rope (2g) - 50 feet of rope");
        Debug.Log("- Torch (1g) - Provides light");
        Debug.Log("- Lockpicks (8g) - For opening locks");
        Debug.Log("- Camping Kit (15g) - For resting outdoors");
        Debug.Log("- Waterskin (3g) - Holds water");
    }

    [ContextMenu("Setup Shop Manager")]
    public void SetupShopManager()
    {
        var shopManager = FindFirstObjectByType<TownShopManager>();
        if (shopManager == null)
        {
            var shopManagerGO = new GameObject("ShopManager");
            shopManagerGO.transform.SetParent(transform);
            shopManager = shopManagerGO.AddComponent<TownShopManager>();
        }

        // Create the shops array
        var shops = new List<TownShop>();
        if (weaponShop != null) shops.Add(weaponShop);
        if (armorShop != null) shops.Add(armorShop);
        if (potionShop != null) shops.Add(potionShop);
        if (generalStore != null) shops.Add(generalStore);

        shopManager.allShops = shops.ToArray();

        // Try to link UI
        var uiDocument = FindFirstObjectByType<UIDocument>();
        if (uiDocument != null)
        {
            shopManager.townUI = uiDocument;
        }

        Debug.Log($"Setup shop manager with {shops.Count} shops");
    }
}
