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

namespace Elfisa.UI.Controls
{
    /// <summary>
    /// Верхняя синяя шапка как в оригинале: 3 равные кнопки, owner-draw + плавный hover (Fluent).
    /// </summary>
    public class ModernAppHeader : Panel
    {
        private readonly List<SidebarItem> _items = new List<SidebarItem>();
        private readonly Dictionary<string, Rectangle> _hitAreas = new Dictionary<string, Rectangle>();
        private readonly AnimationTimer _hoverAnim;
        private ThemeColors _theme;
        private string _activeKey;
        private string _hoverKey;
        private float _hoverProgress;

        public event EventHandler<string> ItemSelected;

        public ModernAppHeader()
        {
            Height = 78;
            Dock = DockStyle.Top;
            Cursor = Cursors.Hand;
            SetStyle(ControlStyles.AllPaintingInWmPaint |
                     ControlStyles.UserPaint |
                     ControlStyles.OptimizedDoubleBuffer |
                     ControlStyles.ResizeRedraw, true);
            _hoverAnim = new AnimationTimer(v =>
            {
                _hoverProgress = v;
                Invalidate();
            });
        }

        public void SetItems(IEnumerable<SidebarItem> items)
        {
            _items.Clear();
            _items.AddRange(items);
            Invalidate();
        }

        public void SetActive(string key)
        {
            _activeKey = key;
            Invalidate();
        }

        public void ApplyTheme(ThemeColors theme)
        {
            _theme = theme;
            Invalidate();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            var theme = _theme ?? ThemeManager.Colors;
            var g = e.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;

            var rect = ClientRectangle;
            using (var brush = new LinearGradientBrush(rect, theme.TitleBarTop, theme.TitleBarBottom, 90f))
            {
                g.FillRectangle(brush, rect);
            }

            using (var sheen = new LinearGradientBrush(
                new Rectangle(0, 0, Width, Height / 2),
                Color.FromArgb(28, 255, 255, 255),
                Color.FromArgb(0, 255, 255, 255),
                LinearGradientMode.Vertical))
            {
                g.FillRectangle(sheen, 0, 0, Width, Height / 2);
            }

            if (_items.Count == 0)
            {
                return;
            }

            _hitAreas.Clear();
            var gap = 8;
            var btnWidth = (Width - gap * (_items.Count + 1)) / _items.Count;
            var btnHeight = Height - 12;
            var top = 6;

            using (var iconFont = new Font("Segoe MDL2 Assets", 18f))
            using (var textFont = new Font("Segoe UI", 10f, FontStyle.Bold))
            {
                for (var i = 0; i < _items.Count; i++)
                {
                    var item = _items[i];
                    var btnRect = new Rectangle(gap + i * (btnWidth + gap), top, btnWidth, btnHeight);
                    _hitAreas[item.Key] = btnRect;

                    var isActive = item.Key == _activeKey;
                    var isHover = item.Key == _hoverKey;
                    var hoverBoost = isHover ? _hoverProgress * 0.22f : 0f;
                    var baseAlpha = isActive ? 0.28f : 0.08f;
                    var alpha = (int)(255 * Math.Min(0.55f, baseAlpha + hoverBoost));
                    var fill = Color.FromArgb(alpha, 255, 255, 255);

                    using (var fillBrush = new SolidBrush(fill))
                    {
                        GraphicsExtensions.FillRoundedRectangle(g, fillBrush, btnRect, theme.CornerRadiusSmall);
                    }

                    if (isActive)
                    {
                        using (var pen = new Pen(Color.FromArgb(180, 255, 255, 255), 1f))
                        {
                            GraphicsExtensions.DrawRoundedRectangle(g, pen, btnRect, theme.CornerRadiusSmall);
                        }
                    }
                    else if (isHover && _hoverProgress > 0.05f)
                    {
                        using (var pen = new Pen(Color.FromArgb((int)(120 * _hoverProgress), 255, 255, 255), 1f))
                        {
                            GraphicsExtensions.DrawRoundedRectangle(g, pen, btnRect, theme.CornerRadiusSmall);
                        }
                    }

                    var iconRect = new Rectangle(btnRect.X, btnRect.Y + 8, btnRect.Width, 26);
                    var textRect = new Rectangle(btnRect.X, btnRect.Y + 34, btnRect.Width, btnRect.Height - 34);

                    if (!string.IsNullOrEmpty(item.IconGlyph))
                    {
                        TextRenderer.DrawText(
                            g,
                            item.IconGlyph,
                            iconFont,
                            iconRect,
                            Color.White,
                            TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine);
                    }

                    TextRenderer.DrawText(
                        g,
                        item.Text,
                        textFont,
                        textRect,
                        Color.White,
                        TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine);
                }
            }
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            var key = HitTest(e.Location);
            if (key != _hoverKey)
            {
                _hoverKey = key;
                _hoverAnim.AnimateTo(string.IsNullOrEmpty(key) ? 0f : 1f, 160);
            }

            base.OnMouseMove(e);
        }

        protected override void OnMouseLeave(EventArgs e)
        {
            _hoverKey = null;
            _hoverAnim.AnimateTo(0f, 160);
            base.OnMouseLeave(e);
        }

        protected override void OnMouseClick(MouseEventArgs e)
        {
            var key = HitTest(e.Location);
            if (!string.IsNullOrEmpty(key))
            {
                SetActive(key);
                ItemSelected?.Invoke(this, key);
            }

            base.OnMouseClick(e);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _hoverAnim.Dispose();
            }

            base.Dispose(disposing);
        }

        private string HitTest(Point location)
        {
            foreach (var pair in _hitAreas)
            {
                if (pair.Value.Contains(location))
                {
                    return pair.Key;
                }
            }

            return null;
        }
    }
}
