using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Elfisa.UI.Theming;

namespace Elfisa.UI.Controls
{
    public class ModernSidebar : Panel
    {
        private readonly FlowLayoutPanel _flow;
        private readonly Dictionary<string, ModernButton> _buttons = new Dictionary<string, ModernButton>();
        private ThemeColors _theme;
        private string _activeKey;

        public event EventHandler<string> ItemSelected;

        public ModernSidebar()
        {
            Width = 220;
            Dock = DockStyle.Left;
            Padding = new Padding(12, 16, 12, 16);
            _flow = new FlowLayoutPanel
            {
                Dock = DockStyle.Fill,
                FlowDirection = FlowDirection.TopDown,
                WrapContents = false,
                AutoScroll = true
            };
            Controls.Add(_flow);
        }

        public void SetItems(IEnumerable<SidebarItem> items)
        {
            _flow.Controls.Clear();
            _buttons.Clear();

            foreach (var item in items)
            {
                var button = new ModernButton
                {
                    SidebarMode = true,
                    Text = "  " + item.Text,
                    Width = 188,
                    Height = 42,
                    Tag = item.Key,
                    TextAlign = ContentAlignment.MiddleLeft,
                    Margin = new Padding(0, 0, 0, 6)
                };
                button.Click += (_, __) => SetActive(item.Key);
                _buttons[item.Key] = button;
                _flow.Controls.Add(button);
            }
        }

        public void SetActive(string key)
        {
            _activeKey = key;
            RefreshButtonStates();
            ItemSelected?.Invoke(this, key);
        }

        public void ApplyTheme(ThemeColors theme)
        {
            _theme = theme;
            BackColor = theme.SidebarBackground;
            _flow.BackColor = theme.SidebarBackground;
            RefreshButtonStates();
        }

        private void RefreshButtonStates()
        {
            var theme = _theme ?? ThemeManager.Colors;
            foreach (var pair in _buttons)
            {
                pair.Value.ApplyTheme(theme);
                pair.Value.IsActiveItem = pair.Key == _activeKey;
            }
        }
    }
}
