using System;
using System.Collections.Generic;
using Net.Eagle0.Eagle.Views;
using TMPro;
using UnityEngine;

namespace eagle {
    /// <summary>
    /// Displays a vertical list of battle progress bars for all ongoing battles.
    /// Each entry shows the province name, a defender/attacker balance bar,
    /// and an action button (Fight!/Waiting.../Observe) for each battle.
    /// </summary>
    public class BattleProgressPanel : MonoBehaviour {
        public GameObject rowPrefab;
        public TMP_Text dayLabel;
        public Transform rowContainer;

        private readonly List<BattleProgressRowController> _rows =
                new List<BattleProgressRowController>();

        private Action<string> _goToBattleAction;

        public void SetGoToBattleAction(Action<string> action) { _goToBattleAction = action; }

        public void
        UpdateBattles(IList<ShardokBattleView> battles, IGameModel model, int battleDay) {
            dayLabel.text = $"Day {battleDay}";

            // Clear stale children left over from scene/prefab (e.g. after reload)
            if (_rows.Count == 0) {
                for (int i = rowContainer.childCount - 1; i >= 0; i--) {
                    Destroy(rowContainer.GetChild(i).gameObject);
                }
            }

            // Remove excess rows
            while (_rows.Count > battles.Count) {
                Destroy(_rows[_rows.Count - 1].gameObject);
                _rows.RemoveAt(_rows.Count - 1);
            }

            // Add rows if needed
            while (_rows.Count < battles.Count) {
                var go = Instantiate(rowPrefab, rowContainer);
                _rows.Add(go.GetComponent<BattleProgressRowController>());
            }

            for (int i = 0; i < battles.Count; i++) {
                _rows[i].Populate(battles[i], model, _goToBattleAction);
            }
        }
    }
}
