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

public class ShopUI : MonoBehaviour
{
    [Header("Shop Settings")]
    public Shop currentShop;

    private UIDocument uiDocument;
    private Character currentCharacter;
    private Bank currentBank;
    private Inventory currentInventory;

    // UI Elements
    private VisualElement shopContainer;
    private TextField searchField;
    private DropdownField categoryFilter;
    private ScrollView itemList;
    private Label shopTitle;
    private Label playerMoney;
    private Button closeButton;

    // Current filter state
    private ItemType? currentFilter = null;
    private string currentSearchTerm = "";

    void Awake()
    {
        uiDocument = GetComponent<UIDocument>();
        if (uiDocument == null)
        {
            Debug.LogError("ShopUI requires a UIDocument component");
            return;
        }

        InitializeUI();
    }

    void InitializeUI()
    {
        var root = uiDocument.rootVisualElement;

        shopContainer = root.Q<VisualElement>("ShopContainer");
        searchField = root.Q<TextField>("SearchField");
        categoryFilter = root.Q<DropdownField>("CategoryFilter");
        itemList = root.Q<ScrollView>("ItemList");
        shopTitle = root.Q<Label>("ShopTitle");
        playerMoney = root.Q<Label>("PlayerMoney");
        closeButton = root.Q<Button>("CloseButton");

        // Setup category filter
        if (categoryFilter != null)
        {
            categoryFilter.choices = new List<string> { "All", "Weapons", "Armor", "Miscellaneous" };
            categoryFilter.value = "All";
            categoryFilter.RegisterValueChangedCallback(OnCategoryChanged);
        }

        // Setup search field
        if (searchField != null)
        {
            searchField.RegisterValueChangedCallback(OnSearchChanged);
        }

        // Setup close button
        if (closeButton != null)
        {
            closeButton.clicked += CloseShop;
        }

        // Hide shop initially
        if (shopContainer != null)
        {
            shopContainer.style.display = DisplayStyle.None;
        }
    }

    public void OpenShop(Shop shop, Character character)
    {
        if (shop == null || character == null)
        {
            Debug.LogError("Cannot open shop: missing shop or character");
            return;
        }

        currentShop = shop;
        currentCharacter = character;
        currentBank = character.GetComponent<Bank>();
        currentInventory = character.GetComponent<Inventory>();

        if (currentBank == null)
        {
            Debug.LogError("Character must have a Bank component to use shop");
            return;
        }

        if (currentInventory == null)
        {
            Debug.LogError("Character must have an Inventory component to use shop");
            return;
        }

        // Update UI
        if (shopTitle != null)
        {
            shopTitle.text = shop.shopName;
        }

        UpdatePlayerMoney();
        RefreshItemList();

        // Show shop
        if (shopContainer != null)
        {
            shopContainer.style.display = DisplayStyle.Flex;
        }

        Debug.Log($"Opened {shop.shopName} for {character.CharacterName}");
    }

    public void CloseShop()
    {
        if (shopContainer != null)
        {
            shopContainer.style.display = DisplayStyle.None;
        }

        currentShop = null;
        currentCharacter = null;
        currentBank = null;
        currentInventory = null;

        Debug.Log("Closed shop");
    }

    private void OnCategoryChanged(ChangeEvent<string> evt)
    {
        switch (evt.newValue)
        {
            case "All":
                currentFilter = null;
                break;
            case "Weapons":
                currentFilter = ItemType.Weapon;
                break;
            case "Armor":
                currentFilter = ItemType.Armor;
                break;
            case "Miscellaneous":
                currentFilter = ItemType.Miscellaneous;
                break;
        }

        RefreshItemList();
    }

    private void OnSearchChanged(ChangeEvent<string> evt)
    {
        currentSearchTerm = evt.newValue;
        RefreshItemList();
    }

    private void RefreshItemList()
    {
        if (itemList == null || currentShop == null) return;

        itemList.Clear();

        var filteredItems = currentShop.GetFilteredItems(currentFilter, currentSearchTerm);

        foreach (var item in filteredItems)
        {
            var itemElement = CreateItemElement(item);
            itemList.Add(itemElement);
        }
    }

    private VisualElement CreateItemElement(Item item)
    {
        var container = new VisualElement();
        container.AddToClassList("shop-item");

        // Item info section
        var infoSection = new VisualElement();
        infoSection.AddToClassList("item-info");

        var nameLabel = new Label(item.itemName);
        nameLabel.AddToClassList("item-name");
        infoSection.Add(nameLabel);

        var descriptionLabel = new Label(item.description);
        descriptionLabel.AddToClassList("item-description");
        infoSection.Add(descriptionLabel);

        // Item stats section (for weapons/armor)
        if (item is WeaponItem weapon)
        {
            var statsLabel = new Label($"Damage: {weapon.minDamage}-{weapon.maxDamage}, Range: {weapon.range}, Speed: {weapon.attackSpeed:F1}s");
            statsLabel.AddToClassList("item-stats");
            infoSection.Add(statsLabel);
        }
        else if (item is ArmorItem armor)
        {
            var statsLabel = new Label($"AC: +{armor.armorClass}, Slot: {armor.armorSlot}");
            statsLabel.AddToClassList("item-stats");
            infoSection.Add(statsLabel);
        }

        container.Add(infoSection);

        // Price and buy section
        var buySection = new VisualElement();
        buySection.AddToClassList("buy-section");

        var priceLabel = new Label(item.GetCostString());
        priceLabel.AddToClassList("item-price");
        buySection.Add(priceLabel);

        var buyButton = new Button(() => PurchaseItem(item));
        buyButton.text = "Buy";
        buyButton.AddToClassList("buy-button");

        // Check if player can afford the item
        bool canAfford = item.CanAfford(currentBank);
        buyButton.SetEnabled(canAfford);

        if (!canAfford)
        {
            buyButton.AddToClassList("cannot-afford");
            buyButton.text = "Can't Afford";
        }

        buySection.Add(buyButton);
        container.Add(buySection);

        return container;
    }

    private void PurchaseItem(Item item)
    {
        if (currentBank == null || currentInventory == null || item == null)
        {
            Debug.LogError("Cannot purchase item: missing components");
            return;
        }

        if (!item.CanAfford(currentBank))
        {
            Debug.LogWarning($"Cannot afford {item.itemName}");
            return;
        }

        // Check if inventory has space
        if (!currentInventory.AddItem(item))
        {
            Debug.LogWarning($"No space in inventory for {item.itemName}");
            return;
        }

        // Complete the purchase
        item.Purchase(currentBank);

        UpdatePlayerMoney();
        RefreshItemList(); // Refresh to update affordability

        Debug.Log($"Purchased {item.itemName}");
    }

    private void UpdatePlayerMoney()
    {
        if (playerMoney != null && currentBank != null)
        {
            playerMoney.text = currentBank.GetCurrencyString();
        }
    }
}
