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

namespace UVC.Twin.MonitoringUI
{
    public class SideDrawerController
    {
        private readonly VisualElement _overlay;
        private readonly VisualElement _panel;
        private readonly Button _closeButton;
        private readonly ScrollView _content;
        private bool _isValid;

        public event Action<string> OnDrawerItemSelected;
        public event Action OnDrawerClosed;

        public bool IsOpen { get; private set; }

        public SideDrawerController(VisualElement root)
        {
            _overlay = root.Q<VisualElement>(ElementIds.DrawerOverlay);
            _panel = root.Q<VisualElement>(ElementIds.DrawerPanel);
            _closeButton = root.Q<Button>(ElementIds.BtnDrawerClose);
            _content = root.Q<ScrollView>(ElementIds.DrawerContent);

            if (_overlay == null || _panel == null || _closeButton == null || _content == null)
            {
                Debug.LogError($"[MonitoringUI] SideDrawer: required elements not found " +
                    $"(overlay={_overlay != null}, panel={_panel != null}, close={_closeButton != null}, content={_content != null})");
                return;
            }

            _isValid = true;
            Bind();
        }

        private void Bind()
        {
            _closeButton.clicked += Close;

            _overlay.RegisterCallback<ClickEvent>(evt =>
            {
                if (evt.target == _overlay)
                    Close();
            });
        }

        public void SetItems(IReadOnlyList<NamedItemData> items)
        {
            if (!_isValid) return;

            _content.Clear();

            foreach (var item in items)
            {
                var btn = new Button { text = item.DisplayName };
                btn.AddToClassList(CssClasses.DrawerItem);

                var capturedId = item.Id;
                btn.clicked += () =>
                {
                    OnDrawerItemSelected?.Invoke(capturedId);
                    Close();
                };

                _content.Add(btn);
            }
        }

        public void Open()
        {
            if (!_isValid) return;
            _overlay.RemoveFromClassList(CssClasses.DrawerHidden);
            IsOpen = true;
        }

        public void Close()
        {
            if (!_isValid) return;
            _overlay.AddToClassList(CssClasses.DrawerHidden);
            IsOpen = false;
            OnDrawerClosed?.Invoke();
        }
    }
}
