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

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

        private readonly ProcessCardsRowController _processCardsRow;
        private readonly EquipmentCardsRowController _cardsRow;
        private readonly VisualElement _processCardsSection;
        private readonly VisualElement _equipmentCardsSection;
        private readonly VisualElement _scheduleInfoPanel;
        private ScheduleInfoController _scheduleInfo;
        private bool _isValid;
        private bool _isInProcessCardsView = true;
        private readonly Dictionary<string, string> _cardTitleMap = new();

        public event Action<string> OnProcessCardClicked;
        public event Action<string> OnEquipmentCardClicked;

        public ScheduleInfoController ScheduleInfo => _scheduleInfo;
        public bool IsInProcessCardsView => _isInProcessCardsView;

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

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

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

            _processCardsSection = Root.Q<VisualElement>(ElementIds.ProcessCardsSection);
            _equipmentCardsSection = Root.Q<VisualElement>(ElementIds.EquipmentCardsSection);
            _scheduleInfoPanel = Root.Q<VisualElement>(ElementIds.ScheduleInfoPanel);

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

            // Process cards row
            if (_processCardsSection != null)
            {
                _processCardsRow = new ProcessCardsRowController(_processCardsSection);
                _processCardsRow.OnProcessCardClicked += tabName =>
                {
                    OnProcessCardClicked?.Invoke(tabName);
                };
            }

            // Equipment cards row
            _cardsRow = new EquipmentCardsRowController(_equipmentCardsSection);
            _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);
            };

            if (_scheduleInfoPanel != null)
                _scheduleInfo = new ScheduleInfoController(_scheduleInfoPanel);
        }

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

        public void SetProcessCards(IReadOnlyList<(string TabName, EquipmentCardData Data)> processCards)
        {
            _processCardsRow?.SetCards(processCards);
        }

        public void ShowProcessCardsView()
        {
            _isInProcessCardsView = true;
            if (_processCardsSection != null) _processCardsSection.style.display = DisplayStyle.Flex;
            if (_equipmentCardsSection != null) _equipmentCardsSection.style.display = DisplayStyle.None;
            if (_scheduleInfoPanel != null) _scheduleInfoPanel.style.display = DisplayStyle.None;
        }

        public void ShowEquipmentDetailView()
        {
            _isInProcessCardsView = false;
            if (_processCardsSection != null) _processCardsSection.style.display = DisplayStyle.None;
            if (_equipmentCardsSection != null) _equipmentCardsSection.style.display = DisplayStyle.Flex;
            if (_scheduleInfoPanel != null) _scheduleInfoPanel.style.display = DisplayStyle.Flex;
        }

        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);
    }
}
