using System;
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 ModernUploadPanel : Panel
    {
        private readonly ModernButton _uploadBtn;
        private readonly ModernButton _downloadBtn;
        private ThemeColors _theme;
        private string _title = "Синхронизация прайс-листа";
        private string _subtitle = "Обмен данными с сервером: скачайте актуальный прайс или отправьте локальные изменения.";

        public ModernButton UploadButton => _uploadBtn;
        public ModernButton DownloadButton => _downloadBtn;

        public string TitleText
        {
            get => _title;
            set { _title = value ?? string.Empty; Invalidate(); }
        }

        public string SubtitleText
        {
            get => _subtitle;
            set { _subtitle = value ?? string.Empty; Invalidate(); }
        }

        public ModernUploadPanel()
        {
            Dock = DockStyle.Fill;
            Padding = new Padding(24);
            SetStyle(ControlStyles.AllPaintingInWmPaint |
                     ControlStyles.UserPaint |
                     ControlStyles.OptimizedDoubleBuffer |
                     ControlStyles.ResizeRedraw, true);

            _uploadBtn = new ModernButton
            {
                Name = "uploadBtn",
                Text = "Загрузить на сервер",
                ButtonStyle = ModernButtonStyle.Primary,
                Width = 200,
                Height = 40,
                AllowTextEllipsis = false
            };
            _downloadBtn = new ModernButton
            {
                Name = "downloadBtn",
                Text = "Скачать с сервера",
                ButtonStyle = ModernButtonStyle.Secondary,
                Width = 200,
                Height = 40,
                AllowTextEllipsis = false
            };

            Controls.Add(_downloadBtn);
            Controls.Add(_uploadBtn);
            Resize += (_, __) => LayoutButtons();
            LayoutButtons();
        }

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

        private void LayoutButtons()
        {
            var card = GetCardRect();
            var totalWidth = _uploadBtn.Width + 12 + _downloadBtn.Width;
            var left = card.X + Math.Max(24, (card.Width - totalWidth) / 2);
            var top = card.Y + 168;

            _uploadBtn.Location = new Point(left, top);
            _downloadBtn.Location = new Point(left + _uploadBtn.Width + 12, top);
        }

        private Rectangle GetCardRect()
        {
            const int cardW = 560;
            const int cardH = 240;
            var w = Math.Min(cardW, Math.Max(320, Width - 48));
            var h = Math.Min(cardH, Math.Max(200, Height - 48));
            return new Rectangle(
                Math.Max(24, (Width - w) / 2),
                Math.Max(24, (Height - h) / 2),
                w,
                h);
        }

        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 card = GetCardRect();
            using (var shadow = new SolidBrush(Color.FromArgb(18, theme.TextPrimary)))
            {
                GraphicsExtensions.FillRoundedRectangle(
                    g,
                    shadow,
                    new Rectangle(card.X + 3, card.Y + 4, card.Width, card.Height),
                    theme.CornerRadiusMedium);
            }

            using (var fill = new SolidBrush(theme.Surface))
            {
                GraphicsExtensions.FillRoundedRectangle(g, fill, card, theme.CornerRadiusMedium);
            }

            using (var pen = new Pen(theme.Border, 1f))
            {
                GraphicsExtensions.DrawRoundedRectangle(g, pen, card, theme.CornerRadiusMedium);
            }

            var iconRect = new Rectangle(card.X + (card.Width - 44) / 2, card.Y + 28, 44, 44);
            using (var iconBrush = new SolidBrush(theme.AccentPrimarySoft))
            {
                GraphicsExtensions.FillRoundedRectangle(g, iconBrush, iconRect, 12);
            }

            using (var iconFont = new Font("Segoe MDL2 Assets", 18f))
            {
                TextRenderer.DrawText(
                    g,
                    "\uE896",
                    iconFont,
                    iconRect,
                    theme.AccentPrimary,
                    TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine);
            }

            var titleRect = new Rectangle(card.X + 28, card.Y + 84, card.Width - 56, 28);
            TextRenderer.DrawText(
                g,
                _title,
                theme.FontSemibold16,
                titleRect,
                theme.TextPrimary,
                TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis);

            var subRect = new Rectangle(card.X + 36, card.Y + 116, card.Width - 72, 44);
            TextRenderer.DrawText(
                g,
                _subtitle,
                theme.FontRegular13,
                subRect,
                theme.TextMuted,
                TextFormatFlags.HorizontalCenter | TextFormatFlags.WordBreak);
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
            var theme = _theme ?? ThemeManager.Colors;
            using (var brush = new SolidBrush(theme.BackgroundPrimary))
            {
                e.Graphics.FillRectangle(brush, ClientRectangle);
            }
        }
    }
}
