using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class UnitActionSystemUI : MonoBehaviour
{

    [SerializeField] private Transform actionButtonPrefab;
    [SerializeField] private Transform actionButtonContainerTransform;
    [SerializeField] private TextMeshProUGUI actionPointsText;
    private void Start() {
        UnitActionSystem.Instance.OnSelectedUnitChanged += UnitActionSystem_onSelectedUnitChanged;
        UnitActionSystem.Instance.OnSelectedActionChanged += UnitActionSystem_onSelectedActionChanged;
        UnitActionSystem.Instance.OnActionStarted += UnitActionSystem_onActionStarted;
        //TurnSystem.Instance.OnTurnChanged += TurnSystem_OnTurnChanged;
        Unit.OnAnyActionPointsChanged += Unit_OnAnyActionPointsChanged;
        CreateUnitActionButtons();
        UpdateSelectedVisual();
        UpdateActionPointsVisual();
    }
    private void CreateUnitActionButtons() {
        foreach (Transform transform in actionButtonContainerTransform) {
            Destroy(transform.gameObject);
        }
        Unit selectedUnit = UnitActionSystem.Instance.GetSelectedUnit();
        foreach (var action in selectedUnit.GetBaseActionArray()) {
            Transform actionButtonTransform = Instantiate(actionButtonPrefab, actionButtonContainerTransform);
            ActionButtonUI actionButtonUI = actionButtonTransform.GetComponent<ActionButtonUI>();
            actionButtonUI.SetBaseAction(action);
        }
    }

    public void TurnSystem_OnTurnChanged(object sender, EventArgs empty) {
        UpdateActionPointsVisual();
    }
    public void Unit_OnAnyActionPointsChanged(object sender, EventArgs empty) {
        UpdateActionPointsVisual();
    }
    private void UnitActionSystem_onSelectedUnitChanged(object sender, EventArgs empty) {
        CreateUnitActionButtons();
        UpdateSelectedVisual();
        UpdateActionPointsVisual();
    }
    private void UnitActionSystem_onSelectedActionChanged(object sender, EventArgs empty) {
        UpdateSelectedVisual();
    }

    private void UnitActionSystem_onActionStarted(object sender, EventArgs empty) {
        UpdateActionPointsVisual();
    }

    private void UpdateSelectedVisual() {
        foreach (var actionButtonUI in actionButtonContainerTransform.GetComponentsInChildren<ActionButtonUI>()) {
            actionButtonUI.UpdateSelectedVisual();
        }
    }

    private void UpdateActionPointsVisual() {
        Unit selectedUnit = UnitActionSystem.Instance.GetSelectedUnit();
        actionPointsText.text = $"Action Points: {selectedUnit.GetActionPoints()}";

    }
}