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

namespace UVC.Twin.MonitoringUI
{
    public class OverviewPanelController
    {
        public VisualElement Root { get; }

        private readonly EquipmentCardsRowController _cardsRow;
        private ScheduleInfoController _scheduleInfo;
        private bool _isValid;
        private readonly Dictionary<string, string> _cardTitleMap = new();

        public event Action<string> OnEquipmentCardClicked;

        public ScheduleInfoController ScheduleInfo => _scheduleInfo;

        private const string UxmlPath = "UITemplate/UVC/MonitoringUI/OverviewPanel/OverviewPanel";

        public OverviewPanelController(VisualElement parent)
        {
            var tree = Resources.Load<VisualTreeAsset>(UxmlPath);
            if (tree == null)
            {
                Debug.LogError("[MonitoringUI] OverviewPanel: UXML not found at " + UxmlPath);
                Root = new VisualElement();
                parent.Add(Root);
                return;
            }

            Root = tree.CloneTree();
            parent.Add(Root);

            var cardsSection = Root.Q<VisualElement>(ElementIds.EquipmentCardsSection);

            if (cardsSection == null)
            {
                Debug.LogError("[MonitoringUI] OverviewPanel: equipment cards section not found");
                return;
            }

            _cardsRow = new EquipmentCardsRowController(cardsSection);
            _isValid = true;

            _cardsRow.OnCardClicked += cardId =>
            {
                if (_scheduleInfo != null
                    && _scheduleInfo.ActiveToggle == ScheduleToggleModes.Equipment
                    && _cardTitleMap.TryGetValue(cardId, out var title))
                {
                    _scheduleInfo.SelectEquipment(title);
                    _scheduleInfo.SelectDate(DateTime.Today.ToString("yyyy-MM-dd"));
                }
                OnEquipmentCardClicked?.Invoke(cardId);
            };

            var schedulePanel = Root.Q<VisualElement>(ElementIds.ScheduleInfoPanel);
            if (schedulePanel != null)
                _scheduleInfo = new ScheduleInfoController(schedulePanel);
        }

        public void Show() => Root.style.display = DisplayStyle.Flex;
        public void Hide() => Root.style.display = DisplayStyle.None;

        public void SetEquipmentCards(IReadOnlyList<EquipmentCardData> cards)
        {
            if (!_isValid) return;

            _cardTitleMap.Clear();
            foreach (var card in cards)
                _cardTitleMap[card.Id] = card.Title;

            _cardsRow.SetCards(cards);
        }

        public void SetScheduleRows(IReadOnlyList<ScheduleRowData> rows)
            => _scheduleInfo?.SetScheduleRows(rows);

        public void SetCurrentDate(string dateText)
            => _scheduleInfo?.SetCurrentDate(dateText);
    }
}
