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

public class TownManager : MonoBehaviour
{
    [Header("Town Configuration")]
    public string townName = "Haven Village";
    public bool hasHarbor = true;

    [Header("UI References")]
    public UIDocument townUI;
    public Camera townCamera;

    [Header("Shop Manager")]
    public TownShopManager shopManager;

    [Header("Team Reference")]
    [HideInInspector]
    public TeamCharacter[] currentTeam;

    private VisualElement rootElement;

    void Start()
    {
        InitializeTown();
        SetupUI();
        LoadTeamData();
    }

    private void InitializeTown()
    {
        // Check if we have settlement context data
        if (SettlementContext.Instance != null)
        {
            // Use data from settlement context
            townName = SettlementContext.Instance.settlementName;
            hasHarbor = SettlementContext.Instance.hasHarbor;

            Debug.Log($"Initialized {townName} ({SettlementContext.Instance.settlementType}) from SettlementContext");

            // Update UI with settlement name
            UpdateTownNameDisplay();
        }
        else
        {
            Debug.Log($"Initialized {townName} (no SettlementContext - using defaults)");
        }

        // Initialize shop manager if not already done
        if (shopManager == null)
        {
            // First check if singleton instance exists
            if (TownShopManager.Instance != null)
            {
                shopManager = TownShopManager.Instance;
                Debug.Log("TownManager: Using existing TownShopManager singleton");
            }
            else
            {
                // Try to find any existing instance in scene
                shopManager = FindFirstObjectByType<TownShopManager>();
                if (shopManager != null)
                {
                    Debug.Log("TownManager: Found existing TownShopManager in scene");
                }
            }
        }

        // If we still don't have a shop manager, create one
        if (shopManager == null)
        {
            Debug.Log("TownManager: Creating new TownShopManager");
            GameObject shopManagerObj = new GameObject("TownShopManager");
            shopManager = shopManagerObj.AddComponent<TownShopManager>();
            shopManager.townUI = townUI;
        }
        else
        {
            Debug.Log($"TownManager: Using existing TownShopManager: {shopManager.gameObject.name}");
            // Make sure the existing manager has the correct UI reference
            if (shopManager.townUI == null)
            {
                shopManager.townUI = townUI;
                Debug.Log("TownManager: Updated TownShopManager UI reference");
            }
        }
    }

    private void SetupUI()
    {
        if (townUI == null) return;

        rootElement = townUI.rootVisualElement;

        UpdateTownNameDisplay();

        // Let TownShopManager handle building interactions
    }

    private void UpdateTownNameDisplay()
    {
        if (rootElement == null) return;

        var townNameLabel = rootElement.Q<Label>("TownNameLabel");
        if (townNameLabel != null)
            townNameLabel.text = townName;
    }

    private void LoadTeamData()
    {
        // Load team data from GameStateManager or PlayerPrefs
        var gameStateManager = FindFirstObjectByType<GameStateManager>();
        if (gameStateManager != null && gameStateManager.savedTeam != null)
        {
            currentTeam = gameStateManager.savedTeam;
            Debug.Log($"Loaded team data: {currentTeam.Length} characters");
        }
        else
        {
            Debug.LogWarning("No team data found, using test data");
            CreateTestTeamData();
        }

        // Update money display
        UpdateMoneyDisplay();
    }

    private void CreateTestTeamData()
    {
        currentTeam = new TeamCharacter[1];
        currentTeam[0] = new TeamCharacter("Test Hero", true)
        {
            gold = 100,
            silver = 50,
            copper = 25
        };
    }

    private void UpdateMoneyDisplay()
    {
        //if (shopManager != null)
        //{
        //    shopManager.UpdateMoneyDisplay();
        //}
    }

    private void SaveTeamData()
    {
        var gameStateManager = FindFirstObjectByType<GameStateManager>();
        if (gameStateManager != null)
        {
            gameStateManager.savedTeam = currentTeam;
            // Trigger save to PlayerPrefs if needed
        }
    }

    // Called by TownShopManager when a building is clicked
    public void OnBuildingClicked(TownShop shop)
    {
        Debug.Log($"TownManager: Shop clicked: {shop.buildingName} - handled by TownShopManager");
        // No longer creating duplicate UI here - TownShopManager handles shop opening
    }

    private void OpenShopDirect(TownShop shop)
    {
        // Find existing UI document from the town UI
        var existingUIDoc = FindFirstObjectByType<UIDocument>();

        // Create shop UI GameObject as a separate top-level object
        var shopUIObject = new GameObject("TownShopUI");

        // Add UIDocument component and load the UXML
        var uiDocument = shopUIObject.AddComponent<UIDocument>();

        // Copy settings from existing UI document if available
        if (existingUIDoc != null)
        {
            uiDocument.panelSettings = existingUIDoc.panelSettings;
            uiDocument.sortingOrder = existingUIDoc.sortingOrder + 100; // Ensure it's on top
        }

        uiDocument.visualTreeAsset = Resources.Load<VisualTreeAsset>("UI/TownShopUI");

        Debug.Log($"Loaded UXML asset: {uiDocument.visualTreeAsset != null}");

        // If not found in Resources, try direct path
        if (uiDocument.visualTreeAsset == null)
        {
#if UNITY_EDITOR
            uiDocument.visualTreeAsset = UnityEditor.AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/TownShopUI.uxml");
            Debug.Log($"Loaded UXML from Assets: {uiDocument.visualTreeAsset != null}");
#endif
        }

        if (uiDocument.visualTreeAsset == null)
        {
            Debug.LogError("Failed to load TownShopUI UXML!");
            Destroy(shopUIObject);
            return;
        }

        // Add TownShopUI component 
        var shopUI = shopUIObject.AddComponent<TownShopUI>();

        // CRITICAL: Force the UIDocument to initialize properly
        uiDocument.enabled = true;

        // Set up the shop UI
        shopUI.SetShop(shop);

        // Add a small delay to ensure everything is properly set up
        StartCoroutine(OpenShopAfterFrame(shopUI));

        // Find first available team member as customer
        if (GameStateManager.Instance?.savedTeam != null)
        {
            foreach (var character in GameStateManager.Instance.savedTeam)
            {
                if (character != null)
                {
                    shopUI.SetCustomer(character);
                    break;
                }
            }
        }

        // Add a small delay to ensure everything is properly set up
        StartCoroutine(OpenShopAfterFrame(shopUI));

        Debug.Log($"Opened shop UI for {shop.buildingName} with sortOrder: {uiDocument.sortingOrder}");
    }

    private System.Collections.IEnumerator OpenShopAfterFrame(TownShopUI townShopUI)
    {
        yield return null; // Wait one frame for UI to initialize
        townShopUI.OpenShop();
        Debug.Log("Shop opened after frame delay");
    }

    public void ReturnToMap()
    {
        SaveTeamData();
        UnityEngine.SceneManagement.SceneManager.LoadScene("MapScene2");
    }
}
