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

namespace UVC.Twin.MonitoringUI
{
    [RequireComponent(typeof(UIDocument))]
    public class MonitoringUIController : MonoBehaviour
    {
        [SerializeField] private MonitoringUIConfig _config;

        private UIDocument _uiDocument;
        private VisualElement _rootElement;

        private TopNavBarController _topNavBar;
        private LeftSidebarController _leftSidebar;
        private SideDrawerController _sideDrawer;
        private OverviewPanelController _overviewPanel;

        private Dictionary<string, ShortcutTabMapping> _shortcutTabMap;
        private Dictionary<string, List<EquipmentCardData>> _bayEquipmentMap = new();

        public MonitoringUIEvents Events { get; } = new MonitoringUIEvents();

        private void OnEnable()
        {
            _uiDocument = GetComponent<UIDocument>();
            _rootElement = _uiDocument.rootVisualElement;

            if (!InitializeControllers())
            {
                Debug.LogError("[MonitoringUI] Initialization failed, controller disabled");
                return;
            }

            WireEvents();
            LoadConfig();
            Debug.Log("[MonitoringUI] Initialized successfully");
        }

        private void OnDisable()
        {
            _topNavBar = null;
            _leftSidebar = null;
            _sideDrawer = null;
            _overviewPanel = null;
            _shortcutTabMap = null;
            _bayEquipmentMap.Clear();
        }

        private bool InitializeControllers()
        {
            var topNavRoot = _rootElement.Q<VisualElement>(ElementIds.TopNavBar);
            if (topNavRoot == null)
            {
                Debug.LogError($"[MonitoringUI] Required element '{ElementIds.TopNavBar}' not found");
                return false;
            }
            _topNavBar = new TopNavBarController(topNavRoot);

            var sidebarRoot = _rootElement.Q<VisualElement>(ElementIds.LeftSidebar);
            if (sidebarRoot == null)
            {
                Debug.LogError($"[MonitoringUI] Required element '{ElementIds.LeftSidebar}' not found");
                return false;
            }
            _leftSidebar = new LeftSidebarController(sidebarRoot);

            _sideDrawer = new SideDrawerController(_rootElement);

            var panelContainer = _rootElement.Q<VisualElement>(ElementIds.MainContentPanelContainer);
            if (panelContainer != null)
            {
                _overviewPanel = new OverviewPanelController(panelContainer);

                _overviewPanel.OnEquipmentCardClicked += cardId =>
                {
                    Debug.Log($"[MonitoringUI] Equipment card clicked: {cardId}");
                    Events.RaiseEquipmentCardSelected(cardId);
                };

                if (_overviewPanel.ScheduleInfo != null)
                {
                    _overviewPanel.ScheduleInfo.OnToggleChanged += mode =>
                    {
                        Debug.Log($"[MonitoringUI] Schedule toggle: {mode}");
                        Events.RaiseScheduleToggleChanged(mode);
                    };
                    _overviewPanel.ScheduleInfo.OnDateOffsetChanged += offset =>
                    {
                        Debug.Log($"[MonitoringUI] Schedule date nav: {offset}");
                        Events.RaiseScheduleDateNavigated(offset);
                    };
                    _overviewPanel.ScheduleInfo.OnEquipmentFilterChanged += name =>
                    {
                        Debug.Log($"[MonitoringUI] Schedule equipment filter: {name}");
                        Events.RaiseScheduleEquipmentFilterChanged(name);
                    };
                    _overviewPanel.ScheduleInfo.OnDateFilterChanged += date =>
                    {
                        Debug.Log($"[MonitoringUI] Schedule date filter: {date}");
                        Events.RaiseScheduleDateFilterChanged(date);
                    };
                }
            }
            else
            {
                Debug.LogWarning("[MonitoringUI] MainContent panel container not found, content panels disabled");
            }

            return true;
        }

        private void WireEvents()
        {
            _topNavBar.OnHamburgerClicked += () =>
            {
                Debug.Log("[MonitoringUI] Hamburger clicked");
                if (_sideDrawer.IsOpen)
                    _sideDrawer.Close();
                else
                    _sideDrawer.Open();
            };

            _topNavBar.OnBayTabSelected += bayId =>
            {
                Debug.Log($"[MonitoringUI] Bay tab selected: {bayId}");
                ApplyBayEquipmentCards(bayId);
                Events.RaiseBayViewChange(bayId);
            };

            _topNavBar.OnSettingsClicked += () =>
            {
                Debug.Log("[MonitoringUI] Settings clicked");
                Events.RaiseSettingsRequest();
            };
            _topNavBar.OnVisibilityClicked += () =>
            {
                Debug.Log("[MonitoringUI] Visibility clicked");
                Events.RaiseVisibilityToggle("default");
            };
            _topNavBar.OnUserClicked += () =>
            {
                Debug.Log("[MonitoringUI] User clicked");
                Events.RaiseUserProfileRequest();
            };
            _topNavBar.OnExportClicked += () =>
            {
                Debug.Log("[MonitoringUI] Export clicked");
                Events.RaiseExportRequest();
            };

            _leftSidebar.OnInfoShortcutClicked += OnShortcutSelected;

            _leftSidebar.OnSidebarToggled += expanded =>
            {
                Debug.Log($"[MonitoringUI] Sidebar toggled: {(expanded ? "expanded" : "collapsed")}");
            };

            _sideDrawer.OnDrawerItemSelected += itemId =>
            {
                Debug.Log($"[MonitoringUI] Drawer item selected: {itemId}");
                Events.RaiseDrawerNavigation(itemId);
            };
        }

        private void LoadConfig()
        {
            if (_config == null)
            {
                Debug.LogWarning("[MonitoringUI] No config assigned, using defaults");
                SetupDefaultData();
                return;
            }

            _shortcutTabMap = new Dictionary<string, ShortcutTabMapping>();
            var shortcuts = new List<InfoShortcutData>();

            foreach (var mapping in _config.ShortcutMappings)
            {
                _shortcutTabMap[mapping.Shortcut.PanelType] = mapping;
                shortcuts.Add(mapping.Shortcut);
            }

            _leftSidebar.SetInfoButtons(shortcuts);
            _sideDrawer.SetItems(_config.DrawerItems);

            if (shortcuts.Count > 0)
            {
                _leftSidebar.SetActiveButton(0);
                var firstPanelType = shortcuts[0].PanelType;
                ApplyTabMapping(firstPanelType);
                ShowOrHideOverviewPanel(firstPanelType);
            }
        }

        private void OnShortcutSelected(string panelType)
        {
            Debug.Log($"[MonitoringUI] Info shortcut clicked: {panelType}");
            Events.RaiseInfoPanelRequest(panelType);
            ApplyTabMapping(panelType);
            ShowOrHideOverviewPanel(panelType);
        }

        private void ShowOrHideOverviewPanel(string panelType)
        {
            if (PanelTypes.IsOverviewPanel(panelType))
                _overviewPanel?.Show();
            else
                _overviewPanel?.Hide();
        }

        private void ApplyTabMapping(string panelType)
        {
            if (_shortcutTabMap == null || !_shortcutTabMap.TryGetValue(panelType, out var mapping))
                return;

            _topNavBar.SetTabs(mapping.Tabs, mapping.DefaultActiveTabId);

            var activeBayId = mapping.DefaultActiveTabId
                ?? (mapping.Tabs.Count > 0 ? mapping.Tabs[0].Id : null);
            if (activeBayId != null)
                ApplyBayEquipmentCards(activeBayId);
        }

        private void ApplyBayEquipmentCards(string bayId)
        {
            if (!_bayEquipmentMap.TryGetValue(bayId, out var cards)) return;
            _overviewPanel?.SetEquipmentCards(cards);
        }

        private void SetupDefaultData()
        {
            _shortcutTabMap = MonitoringUIDefaultData.BuildShortcutTabMap();

            var shortcuts = MonitoringUIDefaultData.BuildShortcutList(_shortcutTabMap);
            _leftSidebar.SetInfoButtons(shortcuts);
            _leftSidebar.SetActiveButton(0);

            _sideDrawer.SetItems(MonitoringUIDefaultData.BuildDrawerItems());

            if (shortcuts.Count > 0)
            {
                var firstPanelType = shortcuts[0].PanelType;
                ApplyTabMapping(firstPanelType);
                ShowOrHideOverviewPanel(firstPanelType);
            }

            SetupDefaultOverviewData();
        }

        public void SetBayTabs(List<NamedItemData> tabs, string activeTabId = null)
        {
            _topNavBar.SetTabs(tabs, activeTabId);
        }

        public void SetBayEquipmentCards(string bayId, List<EquipmentCardData> cards)
        {
            _bayEquipmentMap[bayId] = cards;
            RefreshEquipmentChoicesFromAllBays();
        }

        public void SetInfoShortcuts(List<InfoShortcutData> shortcuts)
        {
            _leftSidebar.SetInfoButtons(shortcuts);
        }

        public void SetDrawerItems(List<NamedItemData> items)
        {
            _sideDrawer.SetItems(items);
        }

        private void SetupDefaultOverviewData()
        {
            if (_overviewPanel == null) return;

            _bayEquipmentMap = MonitoringUIDefaultData.BuildBayEquipmentMap();
            ApplyBayEquipmentCards("trans-bay");

            _overviewPanel.SetScheduleRows(MonitoringUIDefaultData.BuildScheduleRows());
            _overviewPanel.SetCurrentDate(MonitoringUIDefaultData.DefaultCurrentDate);

            RefreshEquipmentChoicesFromAllBays();
            _overviewPanel.ScheduleInfo?.SetDateChoices(
                MonitoringUIDefaultData.BuildDefaultDateChoices(),
                MonitoringUIDefaultData.DefaultCurrentDate);
        }

        public void SetScheduleData(List<ScheduleRowData> rows)
        {
            _overviewPanel?.SetScheduleRows(rows);
        }

        public void SetScheduleEquipmentChoices(List<string> names, string defaultValue = null)
        {
            _overviewPanel?.ScheduleInfo?.SetEquipmentChoices(names, defaultValue);
        }

        public void SetScheduleDateChoices(List<string> dates, string defaultValue = null)
        {
            _overviewPanel?.ScheduleInfo?.SetDateChoices(dates, defaultValue);
        }

        private void RefreshEquipmentChoicesFromAllBays()
        {
            if (_overviewPanel == null) return;

            var equipmentNames = new HashSet<string>();
            foreach (var cards in _bayEquipmentMap.Values)
            {
                foreach (var card in cards)
                {
                    if (!card.IsSummaryCard)
                        equipmentNames.Add(card.Title);
                }
            }

            var sorted = equipmentNames.OrderBy(n => n).ToList();
            _overviewPanel.ScheduleInfo?.SetEquipmentChoices(sorted);
        }

        public void ExpandSidebar() => _leftSidebar.Expand();

        public void CollapseSidebar() => _leftSidebar.Collapse();
    }
}
