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

namespace UVC.Twin.MonitoringUI
{
    public class LeftSidebarController
    {
        private readonly VisualElement _root;
        private readonly VisualElement _infoButtonsContainer;
        private readonly Button _toggleButton;
        private readonly Label _toggleIcon;
        private readonly List<VisualElement> _infoRows = new();
        private bool _isExpanded;
        private bool _isValid;

        public event Action<int> OnMenuItemSelected;
        public event Action<bool> OnSidebarToggled;

        public bool IsExpanded => _isExpanded;

        public LeftSidebarController(VisualElement root)
        {
            _root = root;

            _infoButtonsContainer = _root.Q<VisualElement>(ElementIds.InfoButtons);
            _toggleButton = _root.Q<Button>(ElementIds.BtnSidebarToggle);
            _toggleIcon = _root.Q<Label>(ElementIds.SidebarToggleIcon);

            if (_infoButtonsContainer == null || _toggleButton == null || _toggleIcon == null)
            {
                Debug.LogError($"[MonitoringUI] LeftSidebar: required elements not found " +
                    $"(infoButtons={_infoButtonsContainer != null}, toggle={_toggleButton != null}, icon={_toggleIcon != null})");
                return;
            }

            _isValid = true;
            _toggleIcon.text = "\u203A"; // ›
            Bind();
        }

        private void Bind()
        {
            _toggleButton.clicked += ToggleSidebar;
        }

        public void SetMenuItems(IReadOnlyList<SideMenuItem> items)
        {
            if (!_isValid) return;

            _infoButtonsContainer.Clear();
            _infoRows.Clear();

            for (int i = 0; i < items.Count; i++)
            {
                var item = items[i];

                var row = new VisualElement();
                row.AddToClassList(CssClasses.InfoButtonRow);

                var dot = new VisualElement();
                dot.AddToClassList(CssClasses.InfoDot);

                var dotLabel = new Label { text = item.Label };
                dotLabel.AddToClassList(CssClasses.InfoDotLabel);
                dot.Add(dotLabel);

                var textLabel = new Label { text = item.DisplayName };
                textLabel.AddToClassList(CssClasses.InfoTextLabel);

                row.Add(dot);
                row.Add(textLabel);

                var capturedIndex = i;
                var capturedRow = row;
                row.RegisterCallback<ClickEvent>(evt =>
                {
                    SetActiveRow(capturedRow);
                    OnMenuItemSelected?.Invoke(capturedIndex);
                });

                _infoButtonsContainer.Add(row);
                _infoRows.Add(row);
            }
        }

        public void SetActiveButton(int index)
        {
            if (index >= 0 && index < _infoRows.Count)
                SetActiveRow(_infoRows[index]);
        }

        private void SetActiveRow(VisualElement activeRow)
        {
            foreach (var row in _infoRows)
            {
                if (row == activeRow)
                    row.AddToClassList(CssClasses.InfoButtonRowActive);
                else
                    row.RemoveFromClassList(CssClasses.InfoButtonRowActive);
            }
        }

        private void ToggleSidebar()
        {
            _isExpanded = !_isExpanded;

            if (_isExpanded)
            {
                _root.RemoveFromClassList(CssClasses.SidebarCollapsed);
                _root.AddToClassList(CssClasses.SidebarExpanded);
                _toggleIcon.text = "\u2039"; // ‹
            }
            else
            {
                _root.RemoveFromClassList(CssClasses.SidebarExpanded);
                _root.AddToClassList(CssClasses.SidebarCollapsed);
                _toggleIcon.text = "\u203A"; // ›
            }

            OnSidebarToggled?.Invoke(_isExpanded);
        }

        public void Expand()
        {
            if (!_isExpanded)
                ToggleSidebar();
        }

        public void Collapse()
        {
            if (_isExpanded)
                ToggleSidebar();
        }
    }
}
