using System;
using System.Collections.Generic;
using Actions;
using TMPro;
using UnityEngine;
using UnityEngine.Serialization;

namespace UI {
    public class UnitActionSystemUI : MonoBehaviour {
        [FormerlySerializedAs("ActionButtonPrefab")] [SerializeField] private Transform actionButtonPrefab;
        [FormerlySerializedAs("ActionButtonContainerTransform")] [SerializeField] private Transform actionButtonContainerTransform;
        [FormerlySerializedAs("ActionPointsText")] [SerializeField] private TextMeshProUGUI actionPointsText;

        private List<ActionButtonUI> actionButtonUIList;

        private void Awake() => actionButtonUIList = new();

        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();
            UpdateActionPoints();
            UpdateSelectedVisual();
        }

        private void Unit_OnAnyActionPointsChanged(object sender, EventArgs e) => UpdateActionPoints();

        private void TurnSystem_OnTurnChanged(object sender, EventArgs e) => UpdateActionPoints();

        private void UnitActionSystem_OnActionStarted(object sender, EventArgs e) => UpdateActionPoints();

        private void UnitActionSystem_OnSelectedActionChanged(object sender, EventArgs e) => UpdateSelectedVisual();

        private void UnitActionSystem_OnSelectedUnitChanged(object sender, EventArgs e) {
            CreateUnitActionButtons();
            UpdateActionPoints();
            UpdateSelectedVisual();
        }

        private void CreateUnitActionButtons() {
            foreach (Transform buttonTransform in actionButtonContainerTransform) {
                Destroy(buttonTransform.gameObject);
            }

            actionButtonUIList.Clear();

            foreach (BaseAction baseAction in UnitActionSystem.Instance.SelectedUnit.BaseActionArray) {
                Transform actionButtonTransform = Instantiate(actionButtonPrefab, actionButtonContainerTransform);
                ActionButtonUI actionButtonUI = actionButtonTransform.GetComponent<ActionButtonUI>();
                actionButtonUI.SetBaseAction(baseAction);
                actionButtonUIList.Add(actionButtonUI);
            }
        }

        private void UpdateSelectedVisual() {
            foreach (ActionButtonUI actionButtonUI in actionButtonUIList) {
                actionButtonUI.UpdateSelectedVisual();
            }
        }

        private void UpdateActionPoints() => actionPointsText.text = $"Action Points: {UnitActionSystem.Instance.SelectedUnit.ActionPoints.ToString()}";
    }
}