using UnityEngine;
using UnityEngine.UIElements; // Changed from UnityEngine.UI
using System.Collections;
using System;

public class BattleUIManager : MonoBehaviour
{
    public static BattleUIManager Instance { get; private set; }

    [Header("UI Toolkit References")]
    [Tooltip("Assign the UIDocument component from the scene.")]
    public UIDocument uiDocument;

    // UI Toolkit Element references
    private Button runPauseButtonElement;
    private Button advanceButtonElement;

    // Coroutine handle for the advance action
    private Coroutine advanceCoroutineHandle;

    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Debug.LogWarning("Multiple instances of BattleUIManager found. Destroying this one.");
            Destroy(gameObject);
            return;
        }
    }

    void Start()
    {
        uiDocument = GetComponent<UIDocument>();
        if (uiDocument == null)
        {
            Debug.LogError("BattleUIManager: UIDocument is not assigned in the Inspector. Please assign it.");
            SetButtonsInteractable(false); // Attempt to disable if elements were somehow found
            enabled = false;
            return;
        }

        var rootVisualElement = uiDocument.rootVisualElement;
        if (rootVisualElement == null)
        {
            Debug.LogError("BattleUIManager: UIDocument has no rootVisualElement. Ensure UXML is correctly set up.");
            enabled = false;
            return;
        }

        // Query for the buttons by their names defined in UXML
        runPauseButtonElement = rootVisualElement.Q<Button>("RunPauseButton");
        advanceButtonElement = rootVisualElement.Q<Button>("AdvanceActionButton");

        if (runPauseButtonElement == null || advanceButtonElement == null)
        {
            Debug.LogError("BattleUIManager: Could not find 'RunPauseButton' or 'AdvanceActionButton' in the UXML. Check names.");
            SetButtonsInteractable(false);
            enabled = false;
            return;
        }

        if (GameManager.Instance == null)
        {
            Debug.LogError("BattleUIManager: GameManager.Instance is null. Ensure GameManager is in the scene and initialized.");
            SetButtonsInteractable(false);
            enabled = false;
            return;
        }

        // Initialize UI based on GameManager's expected initial state
        runPauseButtonElement.text = "Run";
        advanceButtonElement.SetEnabled(true); // Can advance from initial paused state
        runPauseButtonElement.SetEnabled(true);

        runPauseButtonElement.RegisterCallback<ClickEvent>(evt => OnRunPauseButtonPressed());
        advanceButtonElement.RegisterCallback<ClickEvent>(evt => OnAdvanceActionButtonPressed());
    }

    public void OnRunPauseButtonPressed()
    {
        if (GameManager.Instance == null) return;

        if (GameManager.Instance.isContinuousRunActive) // Was running continuously, now pause
        {
            GameManager.Instance.isContinuousRunActive = false;
            GameManager.Instance.PauseGame();
            runPauseButtonElement.text = "Run";
            advanceButtonElement.SetEnabled(true); // Allow advance when paused
        }
        else // Was paused or not in continuous run, now run continuously
        {
            if (advanceCoroutineHandle != null) // Stop any pending "Advance" action
            {
                StopCoroutine(advanceCoroutineHandle);
                advanceCoroutineHandle = null;
            }
            GameManager.Instance.isContinuousRunActive = true;
            GameManager.Instance.ResumeGame();
            runPauseButtonElement.text = "Pause";
            advanceButtonElement.SetEnabled(false); // Disable advance when in continuous run
        }
    }

    public void OnAdvanceActionButtonPressed()
    {
        // 
        if (GameManager.Instance == null) return;

        if (GameManager.Instance.isContinuousRunActive)
        {
            return;
        }

        // Distable advance button immediately
        SetButtonsInteractable(false);

        CinemachineCameraController.Instance.FrameAllCharacters(GameManager.Instance.GetAllCharacters());

        // If already advancing, stop the current coroutine
        GameManager.Instance.AdvanceAction();

    }

    public void SetButtonsInteractable(bool interactable)
    {
        runPauseButtonElement?.SetEnabled(interactable);
        advanceButtonElement?.SetEnabled(interactable);
    }

    // Call this from GameManager when the battle ends
    public void DisableBattleControls()
    {

        SetButtonsInteractable(false);
        if (runPauseButtonElement != null) runPauseButtonElement.text = "Battle Over";
    }

    void OnDestroy()
    {
        // Clean up listeners if the object is destroyed
        // For UI Toolkit, callbacks are typically managed well by the system, but explicit unregistering can be done if needed.
        // runPauseButtonElement?.UnregisterCallback<ClickEvent>(...); // if you stored the exact lambda or method
        if (Instance == this) // Singleton cleanup
        {
            Instance = null;
        }
    }
}
