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

/// <summary>
/// Simple UI controller for settlement interaction prompts
/// Displays when near a settlement and shows interaction instructions
/// </summary>
public class SettlementInteractionUI : MonoBehaviour
{
    [Header("UI References")]
    [Tooltip("UI Document for settlement interaction prompt")]
    public UIDocument uiDocument;

    [Header("UI Element Names")]
    [Tooltip("Name of the interaction prompt container in UXML")]
    public string promptContainerName = "SettlementPrompt";

    [Tooltip("Name of the settlement name label in UXML")]
    public string settlementNameLabelName = "SettlementName";

    [Tooltip("Name of the interaction instruction label in UXML")]
    public string instructionLabelName = "InteractionInstruction";

    // UI Elements
    private VisualElement promptContainer;
    private Label settlementNameLabel;
    private Label instructionLabel;

    // References
    private SettlementInteractionManager interactionManager;
    private bool eventsSubscribed = false;

    void Start()
    {
        InitializeUI();
        SetupEventListeners();

        // Check for nearby settlements on start
        StartCoroutine(CheckForNearbySettlementOnStart());
    }

    void OnEnable()
    {
        // When returning from a settlement, check if we're still near one
        if (interactionManager != null)
        {
            StartCoroutine(CheckForNearbySettlementOnEnable());
        }
    }

    private IEnumerator CheckForNearbySettlementOnStart()
    {
        // Wait a frame to ensure other systems are ready
        yield return new WaitForEndOfFrame();
        CheckForNearbySettlement();
    }

    private IEnumerator CheckForNearbySettlementOnEnable()
    {
        // Wait a frame to ensure other systems are ready
        yield return new WaitForEndOfFrame();
        CheckForNearbySettlement();
    }

    private void CheckForNearbySettlement()
    {
        // If manager wasn't found during setup, try to find it again
        if (interactionManager == null)
        {
            interactionManager = FindFirstObjectByType<SettlementInteractionManager>();
            if (interactionManager != null && !eventsSubscribed)
            {
                // Subscribe to events now that we found the manager
                interactionManager.OnSettlementDetected += ShowSettlementPrompt;
                interactionManager.OnSettlementLeft += HideSettlementPrompt;
                interactionManager.OnSettlementEntered += OnSettlementEntered;
                eventsSubscribed = true;
                Debug.Log("SettlementInteractionUI: Late connection to SettlementInteractionManager successful");
            }
        }

        if (interactionManager != null)
        {
            var currentSettlement = interactionManager.GetCurrentNearbySettlement();
            if (currentSettlement != null)
            {
                Debug.Log($"SettlementInteractionUI: Found nearby settlement on enable: {currentSettlement.name}");
                ShowSettlementPrompt(currentSettlement);
            }
            else
            {
                Debug.Log("SettlementInteractionUI: No nearby settlement found on enable");
                HideSettlementPrompt();
            }
        }
        else
        {
            Debug.LogWarning("SettlementInteractionUI: Still cannot find SettlementInteractionManager");
        }
    }

    /// <summary>
    /// Initialize UI elements
    /// </summary>
    private void InitializeUI()
    {
        if (uiDocument == null)
        {
            uiDocument = GetComponent<UIDocument>();
        }

        if (uiDocument == null)
        {
            Debug.LogError("SettlementInteractionUI: No UIDocument found!");
            return;
        }

        var root = uiDocument.rootVisualElement;

        // Find UI elements
        promptContainer = root.Q<VisualElement>(promptContainerName);
        settlementNameLabel = root.Q<Label>(settlementNameLabelName);
        instructionLabel = root.Q<Label>(instructionLabelName);

        // Initially hide the prompt
        if (promptContainer != null)
        {
            promptContainer.style.display = DisplayStyle.None;
        }

        Debug.Log("SettlementInteractionUI initialized");
    }

    /// <summary>
    /// Setup event listeners for settlement interaction
    /// </summary>
    private void SetupEventListeners()
    {
        interactionManager = FindFirstObjectByType<SettlementInteractionManager>();

        if (interactionManager != null && !eventsSubscribed)
        {
            interactionManager.OnSettlementDetected += ShowSettlementPrompt;
            interactionManager.OnSettlementLeft += HideSettlementPrompt;
            interactionManager.OnSettlementEntered += OnSettlementEntered;
            eventsSubscribed = true;

            Debug.Log("SettlementInteractionUI connected to SettlementInteractionManager");
        }
        else
        {
            Debug.LogWarning("SettlementInteractionUI: SettlementInteractionManager not found! Will retry in CheckForNearbySettlement");
        }
    }

    /// <summary>
    /// Show settlement interaction prompt
    /// </summary>
    private void ShowSettlementPrompt(Settlement settlement)
    {
        if (promptContainer == null)
        {
            Debug.LogWarning("SettlementInteractionUI: Cannot show prompt - promptContainer is null");
            return;
        }

        if (settlement == null)
        {
            Debug.LogWarning("SettlementInteractionUI: Cannot show prompt - settlement is null");
            return;
        }

        // Update settlement name
        if (settlementNameLabel != null)
        {
            settlementNameLabel.text = settlement.name;
            Debug.Log($"SettlementInteractionUI: Set settlement name to: '{settlement.name}'");
        }
        else
        {
            Debug.LogWarning("SettlementInteractionUI: settlementNameLabel is null");
        }

        // Update interaction instruction
        if (instructionLabel != null)
        {
            string settlementType = settlement.Type == SettlementType.Town ? "Town" : "Village";
            string keyName = interactionManager?.enterSettlementKey.ToString() ?? "E";
            instructionLabel.text = $"Press {keyName} to enter {settlementType}";
            Debug.Log($"SettlementInteractionUI: Set instruction to: '{instructionLabel.text}'");
        }
        else
        {
            Debug.LogWarning("SettlementInteractionUI: instructionLabel is null");
        }

        // Show the prompt
        promptContainer.style.display = DisplayStyle.Flex;

        Debug.Log($"SettlementInteractionUI: Showing prompt for: {settlement.name}");
    }

    /// <summary>
    /// Hide settlement interaction prompt
    /// </summary>
    private void HideSettlementPrompt()
    {
        if (promptContainer != null)
        {
            promptContainer.style.display = DisplayStyle.None;
        }

        Debug.Log("Hiding settlement prompt");
    }

    /// <summary>
    /// Handle settlement entry (cleanup if needed)
    /// </summary>
    private void OnSettlementEntered(Settlement settlement)
    {
        Debug.Log($"Entering settlement: {settlement.name}");
        // UI will be destroyed when scene changes, no cleanup needed
    }

    void OnDestroy()
    {
        // Cleanup event listeners
        if (interactionManager != null && eventsSubscribed)
        {
            interactionManager.OnSettlementDetected -= ShowSettlementPrompt;
            interactionManager.OnSettlementLeft -= HideSettlementPrompt;
            interactionManager.OnSettlementEntered -= OnSettlementEntered;
            eventsSubscribed = false;
        }
    }

    /// <summary>
    /// Force UI to show (for testing or manual control)
    /// </summary>
    public void ForceShowUI()
    {
        if (promptContainer != null)
        {
            promptContainer.style.display = DisplayStyle.Flex;

            // Update with current nearby settlement if available
            if (interactionManager != null)
            {
                var currentSettlement = interactionManager.GetCurrentNearbySettlement();
                if (currentSettlement != null)
                {
                    ShowSettlementPrompt(currentSettlement);
                    return;
                }
            }

            // Fallback: show with generic text
            if (settlementNameLabel != null)
            {
                settlementNameLabel.text = "Nearby Settlement";
            }
            if (instructionLabel != null)
            {
                instructionLabel.text = "Press E to enter";
            }

            Debug.Log("[SettlementUI] Force showing UI");
        }
    }

    /// <summary>
    /// Force UI to hide (for testing or manual control)
    /// </summary>
    public void ForceHideUI()
    {
        if (promptContainer != null)
        {
            promptContainer.style.display = DisplayStyle.None;
            Debug.Log("[SettlementUI] Force hiding UI");
        }
    }

    /// <summary>
    /// Check if UI is currently visible
    /// </summary>
    public bool IsUIVisible()
    {
        return promptContainer != null && promptContainer.style.display == DisplayStyle.Flex;
    }
}
