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

public class TownShopUI : MonoBehaviour
{
    [Header("References")]
    public UIDocument uiDocument;

    [Header("Shop Settings")]
    public TownShop currentShop;
    public TeamCharacter selectedCustomer;

    // UI Elements
    private VisualElement root;
    private VisualElement shopContainer;
    private Label shopNameLabel;
    private Label shopkeeperLabel;
    private VisualElement itemList;
    private VisualElement customerPanel;
    private DropdownField customerDropdown;
    private Label moneyLabel;
    private VisualElement tabContainer;
    private Button buyTab;
    private Button sellTab;
    private DropdownField categoryFilter;
    private TextField searchField;
    private Button closeButton;

    // State
    private bool isSellMode = false;

    private void Start()
    {
        InitializeUI();
        SetupEventHandlers();

        // Try to load team from GameStateManager
        if (GameStateManager.Instance?.savedTeam != null)
        {
            foreach (var character in GameStateManager.Instance.savedTeam)
            {
                if (character != null)
                {
                    selectedCustomer = character;
                    UpdateCustomerDisplay();
                    break;
                }
            }
        }
    }

    public void SetShop(TownShop shop)
    {
        Debug.Log($"=== TownShopUI.SetShop DEBUG ===");
        Debug.Log($"Received shop: {shop?.buildingName ?? "NULL"} ({shop?.shopType})");
        Debug.Log($"Shop keeper: {shop?.shopkeeperName ?? "NULL"}");
        Debug.Log($"Current shop before: {currentShop?.buildingName ?? "NULL"}");

        currentShop = shop;

        Debug.Log($"Current shop after: {currentShop?.buildingName ?? "NULL"}");

        if (root != null)
        {
            UpdateShopDisplay();
            RefreshItemList();
        }
    }

    public void SetCustomer(TeamCharacter customer)
    {
        selectedCustomer = customer;
        UpdateCustomerDisplay();
        RefreshItemList();
    }

    private void InitializeUI()
    {
        if (uiDocument == null)
        {
            uiDocument = GetComponent<UIDocument>();
        }

        if (uiDocument?.rootVisualElement == null)
        {
            Debug.LogError("UI Document or root visual element is null!");
            return;
        }

        // Force refresh the UI Document to ensure proper initialization
        uiDocument.enabled = false;
        uiDocument.enabled = true;

        root = uiDocument.rootVisualElement;
        Debug.Log($"Root element found: {root != null}");

        // Ensure root element is visible and properly configured
        if (root != null)
        {
            root.style.position = Position.Absolute;
            root.style.left = 0;
            root.style.top = 0;
            root.style.right = 0;
            root.style.bottom = 0;
            root.style.visibility = Visibility.Visible;
            root.style.display = DisplayStyle.Flex;
            Debug.Log("Root element visibility and position configured");
        }

        // Get UI elements
        shopContainer = root.Q<VisualElement>("shop-container");
        shopNameLabel = root.Q<Label>("shop-name");
        shopkeeperLabel = root.Q<Label>("shopkeeper-name");
        itemList = root.Q<VisualElement>("item-list");
        customerPanel = root.Q<VisualElement>("customer-panel");
        customerDropdown = root.Q<DropdownField>("customer-dropdown");
        moneyLabel = root.Q<Label>("money-label");
        tabContainer = root.Q<VisualElement>("tab-container");
        buyTab = root.Q<Button>("buy-tab");
        sellTab = root.Q<Button>("sell-tab");
        categoryFilter = root.Q<DropdownField>("category-filter");
        searchField = root.Q<TextField>("search-field");
        closeButton = root.Q<Button>("close-button");

        Debug.Log($"Key UI elements found - shopContainer: {shopContainer != null}, shopNameLabel: {shopNameLabel != null}, buyTab: {buyTab != null}");

        // Set initial visibility
        if (shopContainer != null)
        {
            shopContainer.style.display = DisplayStyle.None;
            Debug.Log("Set shopContainer to hidden initially");
        }
        else
        {
            Debug.LogError("shopContainer not found! Check UXML element names.");
        }

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

        Debug.Log("TownShopUI initialized");
    }

    private void SetupEventHandlers()
    {
        if (buyTab != null)
        {
            buyTab.clicked += SwitchToBuyMode;
        }

        if (sellTab != null)
        {
            sellTab.clicked += SwitchToSellMode;
        }

        if (closeButton != null)
        {
            closeButton.clicked += CloseShop;
        }

        if (customerDropdown != null)
        {
            customerDropdown.RegisterValueChangedCallback(OnCustomerChanged);
        }

        if (categoryFilter != null)
        {
            categoryFilter.RegisterValueChangedCallback(evt => RefreshItemList());
        }

        if (searchField != null)
        {
            searchField.RegisterValueChangedCallback(evt => RefreshItemList());
        }
    }

    public void OpenShop()
    {
        Debug.Log($"=== OpenShop called ===");
        Debug.Log($"shopContainer: {shopContainer != null}");
        Debug.Log($"currentShop: {currentShop?.buildingName ?? "NULL"}");

        if (shopContainer != null)
        {
            shopContainer.style.display = DisplayStyle.Flex;
            Debug.Log("Set shopContainer to visible");
        }
        else
        {
            Debug.LogError("Cannot open shop - shopContainer is null! Creating fallback UI...");
            CreateFallbackUI();
            return;
        }

        PopulateCustomerDropdown();
        UpdateShopDisplay();
        UpdateCustomerDisplay();
        SwitchToBuyMode();
        RefreshItemList();

        Debug.Log("Shop opening sequence completed");
    }

    private void CreateFallbackUI()
    {
        if (root == null) return;

        // Create a simple fallback UI directly in code
        var fallbackContainer = new VisualElement();
        fallbackContainer.style.position = Position.Absolute;
        fallbackContainer.style.width = Length.Percent(100);
        fallbackContainer.style.height = Length.Percent(100);
        fallbackContainer.style.backgroundColor = new Color(0, 0, 0, 0.8f);
        fallbackContainer.style.justifyContent = Justify.Center;
        fallbackContainer.style.alignItems = Align.Center;

        var shopWindow = new VisualElement();
        shopWindow.style.width = 400;
        shopWindow.style.height = 300;
        shopWindow.style.backgroundColor = new Color(0.9f, 0.85f, 0.7f);
        shopWindow.style.borderLeftWidth = 3;
        shopWindow.style.borderRightWidth = 3;
        shopWindow.style.borderTopWidth = 3;
        shopWindow.style.borderBottomWidth = 3;
        shopWindow.style.borderLeftColor = new Color(0.55f, 0.27f, 0.07f);
        shopWindow.style.borderRightColor = new Color(0.55f, 0.27f, 0.07f);
        shopWindow.style.borderTopColor = new Color(0.55f, 0.27f, 0.07f);
        shopWindow.style.borderBottomColor = new Color(0.55f, 0.27f, 0.07f);
        shopWindow.style.borderTopLeftRadius = 10;
        shopWindow.style.borderTopRightRadius = 10;
        shopWindow.style.borderBottomLeftRadius = 10;
        shopWindow.style.borderBottomRightRadius = 10;
        shopWindow.style.paddingLeft = 20;
        shopWindow.style.paddingRight = 20;
        shopWindow.style.paddingTop = 20;
        shopWindow.style.paddingBottom = 20;

        var title = new Label($"{currentShop?.buildingName ?? "Shop"} - FALLBACK UI");
        title.style.fontSize = 20;
        title.style.color = new Color(0.55f, 0.27f, 0.07f);
        title.style.unityFontStyleAndWeight = FontStyle.Bold;
        title.style.marginBottom = 20;

        var message = new Label("The full shop UI failed to load.\nThis is a simplified fallback interface.\nCheck console for details.");
        message.style.fontSize = 14;
        message.style.color = new Color(0.3f, 0.3f, 0.3f);
        message.style.whiteSpace = WhiteSpace.Normal;
        message.style.marginBottom = 20;

        var closeButton = new Button(() =>
        {
            root.Remove(fallbackContainer);
            Destroy(gameObject);
        });
        closeButton.text = "Close";
        closeButton.style.backgroundColor = new Color(0.8f, 0.2f, 0.2f);
        closeButton.style.color = Color.white;
        closeButton.style.borderLeftWidth = 0;
        closeButton.style.borderRightWidth = 0;
        closeButton.style.borderTopWidth = 0;
        closeButton.style.borderBottomWidth = 0;
        closeButton.style.borderTopLeftRadius = 5;
        closeButton.style.borderTopRightRadius = 5;
        closeButton.style.borderBottomLeftRadius = 5;
        closeButton.style.borderBottomRightRadius = 5;
        closeButton.style.width = 80;
        closeButton.style.height = 30;

        shopWindow.Add(title);
        shopWindow.Add(message);
        shopWindow.Add(closeButton);
        fallbackContainer.Add(shopWindow);
        root.Add(fallbackContainer);

        Debug.Log("Fallback UI created and displayed");
    }

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

        // Destroy the entire shop UI GameObject
        Destroy(gameObject);
        Debug.Log("Shop UI closed and destroyed");
    }

    private void PopulateCustomerDropdown()
    {
        if (customerDropdown == null || GameStateManager.Instance?.savedTeam == null) return;

        var choices = new List<string>();
        foreach (var member in GameStateManager.Instance.savedTeam)
        {
            if (member != null)
            {
                choices.Add(member.name); // Using correct property name
            }
        }

        customerDropdown.choices = choices;
        if (choices.Count > 0)
        {
            customerDropdown.value = choices[0];
            if (selectedCustomer == null)
            {
                foreach (var member in GameStateManager.Instance.savedTeam)
                {
                    if (member != null)
                    {
                        selectedCustomer = member;
                        break;
                    }
                }
            }
        }
    }

    private void OnCustomerChanged(ChangeEvent<string> evt)
    {
        if (GameStateManager.Instance?.savedTeam == null) return;

        foreach (var member in GameStateManager.Instance.savedTeam)
        {
            if (member != null && member.name == evt.newValue) // Using correct property name
            {
                selectedCustomer = member;
                UpdateCustomerDisplay();
                RefreshItemList();
                break;
            }
        }
    }

    private void UpdateShopDisplay()
    {
        Debug.Log($"=== UpdateShopDisplay DEBUG ===");
        Debug.Log($"Current shop: {currentShop?.buildingName ?? "NULL"} ({currentShop?.shopType})");
        Debug.Log($"shopNameLabel: {shopNameLabel != null}");
        Debug.Log($"shopkeeperLabel: {shopkeeperLabel != null}");

        if (currentShop == null) return;

        if (shopNameLabel != null)
        {
            shopNameLabel.text = currentShop.buildingName;
            Debug.Log($"Set shop name label to: {currentShop.buildingName}");
        }

        if (shopkeeperLabel != null)
        {
            shopkeeperLabel.text = $"Shopkeeper: {currentShop.shopkeeperName}";
            Debug.Log($"Set shopkeeper label to: {currentShop.shopkeeperName}");
        }
    }

    private void UpdateCustomerDisplay()
    {
        if (selectedCustomer == null) return;

        UpdateMoneyDisplay();
    }

    private void UpdateMoneyDisplay()
    {
        if (moneyLabel == null || selectedCustomer == null) return;

        moneyLabel.text = $"Money: {selectedCustomer.gold}g {selectedCustomer.silver}s {selectedCustomer.copper}c";
    }

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

        itemList.Clear();

        if (isSellMode)
        {
            // Show player inventory for selling
            PopulateSellItems();
        }
        else
        {
            // Show shop inventory for buying
            PopulateBuyItems();
        }
    }

    private void PopulateBuyItems()
    {
        // Get shop inventory using the correct method
        var shopInventory = currentShop.GetInventory();

        foreach (var shopItem in shopInventory)
        {
            if (shopItem == null || shopItem.item == null) continue;

            // Apply filters
            string searchText = searchField?.value?.ToLower() ?? "";
            string selectedCategory = categoryFilter?.value ?? "All";

            if (!string.IsNullOrEmpty(searchText) && !shopItem.item.itemName.ToLower().Contains(searchText))
                continue;

            if (selectedCategory != "All" && !MatchesCategory(shopItem.item, selectedCategory))
                continue;

            CreateShopItemElement(shopItem);
        }
    }

    private void PopulateSellItems()
    {
        if (selectedCustomer == null) return;

        // Get player's inventory items using correct property names
        var playerItems = GetPlayerInventoryItems();
        foreach (var item in playerItems)
        {
            if (item == null) continue;

            // Apply filters
            string searchText = searchField?.value?.ToLower() ?? "";
            string selectedCategory = categoryFilter?.value ?? "All";

            if (!string.IsNullOrEmpty(searchText) && !item.itemName.ToLower().Contains(searchText))
                continue;

            if (selectedCategory != "All" && !MatchesCategory(item, selectedCategory))
                continue;

            CreateSellItemElement(item);
        }
    }

    private List<Item> GetPlayerInventoryItems()
    {
        var items = new List<Item>();

        if (selectedCustomer == null) return items;

        // Note: TeamCharacter stores item names as strings, but we need actual Item objects
        // This is a limitation of the current system - we would need an ItemDatabase
        // to convert item names back to Item objects for proper selling functionality

        // For now, return empty list with a debug message
        if (selectedCustomer.weapons != null && selectedCustomer.weapons.Count > 0)
        {
            Debug.LogWarning("Player has weapons but cannot display them - need ItemDatabase to convert string names to Item objects");
        }

        if (selectedCustomer.armor != null && selectedCustomer.armor.Count > 0)
        {
            Debug.LogWarning("Player has armor but cannot display them - need ItemDatabase to convert string names to Item objects");
        }

        if (selectedCustomer.miscItems != null && selectedCustomer.miscItems.Count > 0)
        {
            Debug.LogWarning("Player has misc items but cannot display them - need ItemDatabase to convert string names to Item objects");
        }

        return items;
    }

    private bool MatchesCategory(Item item, string category)
    {
        switch (category)
        {
            case "Weapons": return item is WeaponItem;
            case "Armor": return item is ArmorItem;
            case "Potions": return item is MiscellaneousItem && item.itemType == ItemType.Consumable;
            case "Misc": return item is MiscellaneousItem;
            default: return true;
        }
    }

    private void CreateShopItemElement(ShopInventoryItem shopItem)
    {
        var itemElement = new VisualElement();
        itemElement.AddToClassList("shop-item");

        // Use flexible row layout
        itemElement.style.flexDirection = FlexDirection.Row;
        itemElement.style.alignItems = Align.Center;
        itemElement.style.justifyContent = Justify.SpaceBetween;
        itemElement.style.paddingTop = 5;
        itemElement.style.paddingBottom = 5;
        itemElement.style.paddingLeft = 10;
        itemElement.style.paddingRight = 10;
        itemElement.style.marginBottom = 3;
        itemElement.style.backgroundColor = new Color(0.95f, 0.95f, 0.95f, 1f);
        itemElement.style.borderBottomWidth = 1;
        itemElement.style.borderBottomColor = new Color(0.8f, 0.8f, 0.8f, 1f);

        // Left side - Item info container
        var infoContainer = new VisualElement();
        infoContainer.style.flexDirection = FlexDirection.Column;
        infoContainer.style.flexGrow = 1;
        infoContainer.style.marginRight = 10;

        var nameLabel = new Label(shopItem.item.itemName);
        nameLabel.AddToClassList("item-name");
        nameLabel.style.fontSize = 14;
        nameLabel.style.color = new Color(0.2f, 0.2f, 0.2f, 1f);
        nameLabel.style.unityFontStyleAndWeight = FontStyle.Bold;

        var descLabel = new Label(shopItem.item.description);
        descLabel.AddToClassList("item-description");
        descLabel.style.fontSize = 12;
        descLabel.style.color = new Color(0.4f, 0.4f, 0.4f, 1f);
        descLabel.style.whiteSpace = WhiteSpace.Normal;

        infoContainer.Add(nameLabel);
        infoContainer.Add(descLabel);

        // Right side - Price and button container
        var actionContainer = new VisualElement();
        actionContainer.style.flexDirection = FlexDirection.Row;
        actionContainer.style.alignItems = Align.Center;
        actionContainer.style.minWidth = 150;

        var priceLabel = new Label(shopItem.GetPriceString());
        priceLabel.AddToClassList("item-price");
        priceLabel.style.fontSize = 12;
        priceLabel.style.color = new Color(0.0f, 0.5f, 0.0f, 1f);
        priceLabel.style.marginRight = 10;
        priceLabel.style.minWidth = 60;

        var buyButton = new Button(() => BuyItem(shopItem))
        {
            text = "Buy"
        };
        buyButton.AddToClassList("buy-button");
        buyButton.style.width = 60;
        buyButton.style.height = 25;
        buyButton.style.fontSize = 12;

        // Check if customer can afford
        if (selectedCustomer != null && !shopItem.CanAfford(selectedCustomer))
        {
            buyButton.SetEnabled(false);
            priceLabel.style.color = new Color(0.8f, 0.2f, 0.2f, 1f);
        }

        actionContainer.Add(priceLabel);
        actionContainer.Add(buyButton);

        itemElement.Add(infoContainer);
        itemElement.Add(actionContainer);

        itemList.Add(itemElement);
    }

    private void CreateSellItemElement(Item item)
    {
        var itemElement = new VisualElement();
        itemElement.AddToClassList("sell-item");

        // Use flexible row layout
        itemElement.style.flexDirection = FlexDirection.Row;
        itemElement.style.alignItems = Align.Center;
        itemElement.style.justifyContent = Justify.SpaceBetween;
        itemElement.style.paddingTop = 5;
        itemElement.style.paddingBottom = 5;
        itemElement.style.paddingLeft = 10;
        itemElement.style.paddingRight = 10;
        itemElement.style.marginBottom = 3;
        itemElement.style.backgroundColor = new Color(0.95f, 0.95f, 0.95f, 1f);
        itemElement.style.borderBottomWidth = 1;
        itemElement.style.borderBottomColor = new Color(0.8f, 0.8f, 0.8f, 1f);

        // Left side - Item info container
        var infoContainer = new VisualElement();
        infoContainer.style.flexDirection = FlexDirection.Column;
        infoContainer.style.flexGrow = 1;
        infoContainer.style.marginRight = 10;

        var nameLabel = new Label(item.itemName);
        nameLabel.AddToClassList("item-name");
        nameLabel.style.fontSize = 14;
        nameLabel.style.color = new Color(0.2f, 0.2f, 0.2f, 1f);
        nameLabel.style.unityFontStyleAndWeight = FontStyle.Bold;

        var descLabel = new Label(item.description);
        descLabel.AddToClassList("item-description");
        descLabel.style.fontSize = 12;
        descLabel.style.color = new Color(0.4f, 0.4f, 0.4f, 1f);
        descLabel.style.whiteSpace = WhiteSpace.Normal;

        infoContainer.Add(nameLabel);
        infoContainer.Add(descLabel);

        // Right side - Price and button container
        var actionContainer = new VisualElement();
        actionContainer.style.flexDirection = FlexDirection.Row;
        actionContainer.style.alignItems = Align.Center;
        actionContainer.style.minWidth = 150;

        var sellPrice = currentShop.GetSellPrice(item);
        var sellPriceGold = sellPrice / 100;
        var sellPriceSilver = (sellPrice % 100) / 10;
        var sellPriceCopper = sellPrice % 10;

        var priceLabel = new Label($"Sell: {sellPriceGold}g {sellPriceSilver}s {sellPriceCopper}c");
        priceLabel.AddToClassList("item-price");
        priceLabel.style.fontSize = 12;
        priceLabel.style.color = new Color(0.0f, 0.5f, 0.0f, 1f);
        priceLabel.style.marginRight = 10;
        priceLabel.style.minWidth = 80;

        var sellButton = new Button(() => SellItem(item))
        {
            text = "Sell"
        };
        sellButton.AddToClassList("sell-button");
        sellButton.style.width = 60;
        sellButton.style.height = 25;
        sellButton.style.fontSize = 12;

        // Check if shop accepts this item
        if (!currentShop.CanBuyItem(item))
        {
            sellButton.SetEnabled(false);
            priceLabel.text = "Not accepted";
            priceLabel.style.color = new Color(0.8f, 0.2f, 0.2f, 1f);
        }

        actionContainer.Add(priceLabel);
        actionContainer.Add(sellButton);

        itemElement.Add(infoContainer);
        itemElement.Add(actionContainer);

        itemList.Add(itemElement);
    }

    private void BuyItem(ShopInventoryItem shopItem)
    {
        if (selectedCustomer == null || shopItem == null) return;

        // Use ShopInventoryItem's Purchase method which handles money transaction
        if (shopItem.CanAfford(selectedCustomer))
        {
            shopItem.Purchase(selectedCustomer);

            // Add item to player's inventory (this needs proper implementation)
            // For now, we'll add to the appropriate string list
            AddItemToPlayerInventory(shopItem.item);

            // Refresh UI
            RefreshItemList();
            UpdateMoneyDisplay();

            Debug.Log($"Bought {shopItem.item.itemName}");
        }
        else
        {
            Debug.Log("Not enough money!");
        }
    }

    private void AddItemToPlayerInventory(Item item)
    {
        if (selectedCustomer == null || item == null) return;

        // Add item name to appropriate list based on item type
        switch (item.itemType)
        {
            case ItemType.Weapon:
                if (selectedCustomer.weapons == null)
                    selectedCustomer.weapons = new List<string>();
                selectedCustomer.weapons.Add(item.itemName);
                break;
            case ItemType.Armor:
                if (selectedCustomer.armor == null)
                    selectedCustomer.armor = new List<string>();
                selectedCustomer.armor.Add(item.itemName);
                break;
            case ItemType.Consumable:
            case ItemType.Miscellaneous:
            case ItemType.Tool:
            case ItemType.Accessory:
                if (selectedCustomer.miscItems == null)
                    selectedCustomer.miscItems = new List<string>();
                selectedCustomer.miscItems.Add(item.itemName);
                break;
        }
    }

    private void SellItem(Item item)
    {
        if (selectedCustomer == null || item == null) return;

        var sellPrice = currentShop.GetSellPrice(item);

        if (sellPrice > 0)
        {
            // Add money to player using the shop's method
            currentShop.SellItemToShop(item, selectedCustomer);

            // Remove item from player inventory
            RemoveItemFromPlayerInventory(item);

            // Refresh UI
            RefreshItemList();
            UpdateMoneyDisplay();

            Debug.Log($"Sold {item.itemName} for {sellPrice / 100}g");
        }
        else
        {
            Debug.Log("Shop doesn't accept this item!");
        }
    }

    private void RemoveItemFromPlayerInventory(Item item)
    {
        if (selectedCustomer == null || item == null) return;

        // Remove item name from appropriate list
        switch (item.itemType)
        {
            case ItemType.Weapon:
                selectedCustomer.weapons?.Remove(item.itemName);
                break;
            case ItemType.Armor:
                selectedCustomer.armor?.Remove(item.itemName);
                break;
            case ItemType.Consumable:
            case ItemType.Miscellaneous:
            case ItemType.Tool:
            case ItemType.Accessory:
                selectedCustomer.miscItems?.Remove(item.itemName);
                break;
        }
    }

    private void SwitchToBuyMode()
    {
        isSellMode = false;

        if (buyTab != null)
        {
            buyTab.AddToClassList("active-tab");
        }

        if (sellTab != null)
        {
            sellTab.RemoveFromClassList("active-tab");
        }

        RefreshItemList();
    }

    private void SwitchToSellMode()
    {
        isSellMode = true;

        if (sellTab != null)
        {
            sellTab.AddToClassList("active-tab");
        }

        if (buyTab != null)
        {
            buyTab.RemoveFromClassList("active-tab");
        }

        RefreshItemList();
    }
}
