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>
    /// Верхняя навигация: бренд + пункты (иконка сверху, подпись снизу).
    /// </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;

        private const int BrandWidth = 118;

        public event EventHandler<string> ItemSelected;

        public ModernAppHeader()
        {
            Height = 64;
            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;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;

            var rect = ClientRectangle;
            // Сплошной основной teal — без градиента, в тон AccentPrimary.
            using (var fill = new SolidBrush(theme.AccentPrimary))
            {
                g.FillRectangle(fill, rect);
            }

            DrawBrand(g, theme);

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

            _hitAreas.Clear();
            const int gap = 6;
            const int padRight = 8;
            var btnHeight = Height - 10;
            var top = 5;
            var x = BrandWidth + 6;

            using (var iconFont = FluentFonts.CreateIconFont(18f))
            using (var textFont = new Font("Segoe UI Semibold", 8.5f, FontStyle.Bold))
            {
                var iconFormat = new StringFormat
                {
                    Alignment = StringAlignment.Center,
                    LineAlignment = StringAlignment.Center,
                    FormatFlags = StringFormatFlags.NoWrap
                };

                // Равная ширина слотов — подписи целиком помещаются на широком окне.
                var available = Math.Max(100, Width - BrandWidth - padRight - 6);
                var btnWidth = Math.Max(72, (available - gap * (_items.Count - 1)) / _items.Count);

                for (var i = 0; i < _items.Count; i++)
                {
                    var item = _items[i];
                    var btnRect = new Rectangle(x, top, btnWidth, btnHeight);
                    _hitAreas[item.Key] = btnRect;
                    x += btnWidth + gap;

                    var isActive = item.Key == _activeKey;
                    var isHover = item.Key == _hoverKey;
                    var hoverBoost = isHover ? _hoverProgress * 0.18f : 0f;
                    var baseAlpha = isActive ? 0.34f : 0.07f;
                    var alpha = (int)(255 * Math.Min(0.52f, baseAlpha + hoverBoost));

                    using (var fillBrush = new SolidBrush(Color.FromArgb(alpha, 255, 255, 255)))
                    {
                        GraphicsExtensions.FillRoundedRectangle(g, fillBrush, btnRect, theme.CornerRadiusSmall);
                    }

                    if (isActive)
                    {
                        using (var pen = new Pen(Color.FromArgb(210, 255, 255, 255), 1.1f))
                        {
                            GraphicsExtensions.DrawRoundedRectangle(g, pen, btnRect, theme.CornerRadiusSmall);
                        }

                        using (var accent = new SolidBrush(Color.FromArgb(235, 255, 255, 255)))
                        {
                            g.FillRectangle(accent, btnRect.X + 10, btnRect.Bottom - 3, btnRect.Width - 20, 2);
                        }
                    }
                    else if (isHover && _hoverProgress > 0.05f)
                    {
                        using (var pen = new Pen(Color.FromArgb((int)(110 * _hoverProgress), 255, 255, 255), 1f))
                        {
                            GraphicsExtensions.DrawRoundedRectangle(g, pen, btnRect, theme.CornerRadiusSmall);
                        }
                    }

                    if (!string.IsNullOrEmpty(item.IconGlyph))
                    {
                        var iconRect = new RectangleF(btnRect.X, btnRect.Y + 4, btnRect.Width, 26);
                        using (var brush = new SolidBrush(Color.White))
                        {
                            g.DrawString(item.IconGlyph, iconFont, brush, iconRect, iconFormat);
                        }
                    }

                    var textRect = new Rectangle(btnRect.X + 2, btnRect.Y + 30, btnRect.Width - 4, btnRect.Height - 34);
                    TextRenderer.DrawText(
                        g,
                        item.Text,
                        textFont,
                        textRect,
                        Color.White,
                        TextFormatFlags.HorizontalCenter | TextFormatFlags.Top | TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine);
                }
            }
        }

        private void DrawBrand(Graphics g, ThemeColors theme)
        {
            var brandRect = new Rectangle(0, 0, BrandWidth, Height);
            using (var dim = new SolidBrush(Color.FromArgb(28, 0, 0, 0)))
            {
                g.FillRectangle(dim, brandRect);
            }

            using (var pen = new Pen(Color.FromArgb(50, 255, 255, 255), 1f))
            {
                g.DrawLine(pen, BrandWidth - 1, 8, BrandWidth - 1, Height - 8);
            }

            var iconSize = 22;
            var iconRect = new Rectangle(12, (Height - iconSize) / 2, iconSize, iconSize);
            using (var iconBrush = new SolidBrush(Color.FromArgb(40, 255, 255, 255)))
            {
                GraphicsExtensions.FillRoundedRectangle(g, iconBrush, iconRect, 6);
            }

            using (var crossPen = new Pen(Color.White, 2f) { StartCap = LineCap.Round, EndCap = LineCap.Round })
            {
                var cx = iconRect.X + iconRect.Width / 2f;
                var cy = iconRect.Y + iconRect.Height / 2f;
                g.DrawLine(crossPen, cx - 5, cy, cx + 5, cy);
                g.DrawLine(crossPen, cx, cy - 5, cx, cy + 5);
            }

            using (var brandFont = new Font("Segoe UI Semibold", 11f, FontStyle.Bold))
            {
                TextRenderer.DrawText(
                    g,
                    "ЭльФиСА",
                    brandFont,
                    new Rectangle(40, 0, BrandWidth - 46, Height),
                    Color.White,
                    TextFormatFlags.VerticalCenter | TextFormatFlags.Left | 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;
        }
    }
}
