using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace AxCopilot.Installer.Offline
{
    /// <summary>
    /// WinForms 기본 MessageBox 대체 커스텀 다이얼로그.
    /// 인스톨러 테마와 일관된 모던 디자인을 제공합니다.
    /// </summary>
    internal sealed class CustomMessageBox : Form
    {
        private DialogResult _result = DialogResult.Cancel;

        private static readonly Color BgColor = Color.FromArgb(26, 27, 46);
        private static readonly Color CardBg = Color.FromArgb(42, 43, 64);
        private static readonly Color AccentCol = Color.FromArgb(75, 94, 252);
        private static readonly Color TextCol = Color.FromArgb(224, 228, 240);
        private static readonly Color SecondaryCol = Color.FromArgb(153, 153, 187);
        private static readonly Color BorderCol = Color.FromArgb(60, 62, 90);

        private CustomMessageBox(string message, string title, MessageBoxButtons buttons, MessageBoxIcon icon)
        {
            Text = title;
            FormBorderStyle = FormBorderStyle.None;
            StartPosition = FormStartPosition.CenterScreen;
            BackColor = BgColor;
            DoubleBuffered = true;
            ShowInTaskbar = false;
            TopMost = true;

            // ── 레이아웃을 TableLayoutPanel으로 구성 (겹침 방지) ──
            var table = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 1,
                RowCount = 3,
                Padding = new Padding(28, 24, 28, 20),
                BackColor = Color.Transparent,
                AutoSize = true,
            };
            table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
            table.RowStyles.Add(new RowStyle(SizeType.AutoSize)); // 제목
            table.RowStyles.Add(new RowStyle(SizeType.AutoSize)); // 메시지
            table.RowStyles.Add(new RowStyle(SizeType.AutoSize)); // 버튼

            // ── Row 0: 아이콘 + 제목 ──
            var titlePanel = new FlowLayoutPanel
            {
                FlowDirection = FlowDirection.LeftToRight,
                AutoSize = true,
                WrapContents = false,
                Margin = new Padding(0, 0, 0, 12),
                BackColor = Color.Transparent,
            };

            var iconText = GetIconPrefix(icon);
            if (!string.IsNullOrEmpty(iconText))
            {
                titlePanel.Controls.Add(new Label
                {
                    Text = iconText,
                    Font = new Font("Segoe UI", 14f),
                    ForeColor = GetIconColor(icon),
                    AutoSize = true,
                    Margin = new Padding(0, 0, 8, 0),
                });
            }

            titlePanel.Controls.Add(new Label
            {
                Text = title,
                Font = new Font("Segoe UI", 12f, FontStyle.Bold),
                ForeColor = TextCol,
                AutoSize = true,
                MaximumSize = new Size(340, 0),
            });
            table.Controls.Add(titlePanel, 0, 0);

            // ── Row 1: 메시지 본문 ──
            var msgLabel = new Label
            {
                Text = message,
                Font = new Font("Segoe UI", 10f),
                ForeColor = TextCol,
                AutoSize = true,
                MaximumSize = new Size(360, 300),
                Margin = new Padding(0, 0, 0, 20),
            };
            table.Controls.Add(msgLabel, 0, 1);

            // ── Row 2: 버튼 영역 ──
            var btnPanel = new FlowLayoutPanel
            {
                FlowDirection = FlowDirection.RightToLeft,
                AutoSize = true,
                WrapContents = false,
                Anchor = AnchorStyles.Right,
                Margin = new Padding(0),
                BackColor = Color.Transparent,
            };

            switch (buttons)
            {
                case MessageBoxButtons.OK:
                    btnPanel.Controls.Add(CreateButton("확인", true, DialogResult.OK));
                    break;
                case MessageBoxButtons.OKCancel:
                    btnPanel.Controls.Add(CreateButton("확인", true, DialogResult.OK));
                    btnPanel.Controls.Add(CreateButton("취소", false, DialogResult.Cancel));
                    break;
                case MessageBoxButtons.YesNo:
                    btnPanel.Controls.Add(CreateButton("예", true, DialogResult.Yes));
                    btnPanel.Controls.Add(CreateButton("아니오", false, DialogResult.No));
                    break;
                case MessageBoxButtons.YesNoCancel:
                    btnPanel.Controls.Add(CreateButton("예", true, DialogResult.Yes));
                    btnPanel.Controls.Add(CreateButton("아니오", false, DialogResult.No));
                    btnPanel.Controls.Add(CreateButton("취소", false, DialogResult.Cancel));
                    break;
            }
            table.Controls.Add(btnPanel, 0, 2);

            Controls.Add(table);

            // ── 크기 계산 (AutoSize 후) ──
            table.PerformLayout();
            var preferred = table.PreferredSize;
            ClientSize = new Size(
                Math.Max(380, Math.Min(preferred.Width + 10, 520)),
                Math.Min(preferred.Height + 10, 500)
            );

            // 드래그 이동
            table.MouseDown += DragForm;
            titlePanel.MouseDown += DragForm;
            msgLabel.MouseDown += DragForm;

            // ESC / Enter
            KeyPreview = true;
            KeyDown += (s, e) =>
            {
                if (e.KeyCode == Keys.Escape)
                {
                    _result = buttons == MessageBoxButtons.YesNo ? DialogResult.No : DialogResult.Cancel;
                    Close();
                }
                else if (e.KeyCode == Keys.Enter)
                {
                    _result = (buttons == MessageBoxButtons.YesNo || buttons == MessageBoxButtons.YesNoCancel)
                        ? DialogResult.Yes : DialogResult.OK;
                    Close();
                }
            };
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            // Region 클리핑 (약간 더 큰 반경으로 잘림 줄임)
            using var clipPath = RoundRect(new Rectangle(0, 0, Width, Height), 18);
            Region = new Region(clipPath);

            var g = e.Graphics;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            // 배경 채우기 (Region 가장자리 보정)
            using var bgBrush = new SolidBrush(BgColor);
            using var bgPath = RoundRect(new Rectangle(0, 0, Width, Height), 18);
            g.FillPath(bgBrush, bgPath);

            // 테두리 (안쪽 1.5px, 부드러운 선)
            using var borderPen = new Pen(Color.FromArgb(80, 90, 140), 1.5f);
            using var borderPath = RoundRect(new Rectangle(1, 1, Width - 3, Height - 3), 16);
            g.DrawPath(borderPen, borderPath);
        }

        private Button CreateButton(string text, bool isPrimary, DialogResult result)
        {
            var btn = new Button
            {
                Text = text,
                Font = new Font("Segoe UI", 10f, isPrimary ? FontStyle.Bold : FontStyle.Regular),
                ForeColor = TextCol,
                BackColor = isPrimary ? AccentCol : CardBg,
                FlatStyle = FlatStyle.Flat,
                Size = new Size(90, 36),
                Margin = new Padding(4, 0, 4, 0),
                Cursor = Cursors.Hand,
            };
            btn.FlatAppearance.BorderSize = 0;
            btn.Click += (s, e) => { _result = result; Close(); };

            btn.Paint += (s, pe) =>
            {
                using var clipPath = RoundRect(new Rectangle(0, 0, btn.Width, btn.Height), 10);
                btn.Region = new Region(clipPath);

                var g = pe.Graphics;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;

                // 배경
                using var fillBrush = new SolidBrush(btn.BackColor);
                using var fillPath = RoundRect(new Rectangle(0, 0, btn.Width, btn.Height), 10);
                g.FillPath(fillBrush, fillPath);

                // 테두리
                using var bPen = new Pen(Color.FromArgb(70, 255, 255, 255), 0.8f);
                using var bPath = RoundRect(new Rectangle(0, 0, btn.Width - 1, btn.Height - 1), 10);
                g.DrawPath(bPen, bPath);

                // 텍스트 직접 그리기
                var sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
                using var textBrush = new SolidBrush(btn.ForeColor);
                g.DrawString(btn.Text, btn.Font, textBrush, new RectangleF(0, 0, btn.Width, btn.Height), sf);
            };

            return btn;
        }

        private static string GetIconPrefix(MessageBoxIcon icon)
        {
            return icon switch
            {
                MessageBoxIcon.Error => "✕",
                MessageBoxIcon.Warning => "⚠",
                MessageBoxIcon.Information => "ℹ",
                MessageBoxIcon.Question => "?",
                _ => "",
            };
        }

        private static Color GetIconColor(MessageBoxIcon icon)
        {
            return icon switch
            {
                MessageBoxIcon.Error => Color.FromArgb(229, 62, 62),
                MessageBoxIcon.Warning => Color.FromArgb(221, 107, 32),
                MessageBoxIcon.Information => Color.FromArgb(75, 94, 252),
                MessageBoxIcon.Question => Color.FromArgb(75, 94, 252),
                _ => TextCol,
            };
        }

        private void DragForm(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                NativeMethods.ReleaseCapture();
                NativeMethods.SendMessage(Handle, 0xA1, (IntPtr)0x2, IntPtr.Zero);
            }
        }

        private static GraphicsPath RoundRect(Rectangle rect, int radius)
        {
            var path = new GraphicsPath();
            var d = radius * 2;
            path.AddArc(rect.X, rect.Y, d, d, 180, 90);
            path.AddArc(rect.Right - d, rect.Y, d, d, 270, 90);
            path.AddArc(rect.Right - d, rect.Bottom - d, d, d, 0, 90);
            path.AddArc(rect.X, rect.Bottom - d, d, d, 90, 90);
            path.CloseFigure();
            return path;
        }

        private static class NativeMethods
        {
            [System.Runtime.InteropServices.DllImport("user32.dll")]
            public static extern bool ReleaseCapture();
            [System.Runtime.InteropServices.DllImport("user32.dll")]
            public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
        }

        // ─── 정적 호출 메서드 (기존 MessageBox.Show 호환) ───────────────

        public static DialogResult Show(string message)
            => Show(message, "AX Copilot", MessageBoxButtons.OK, MessageBoxIcon.None);

        public static DialogResult Show(string message, string title)
            => Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.None);

        public static DialogResult Show(string message, string title, MessageBoxButtons buttons)
            => Show(message, title, buttons, MessageBoxIcon.None);

        public static DialogResult Show(string message, string title, MessageBoxButtons buttons, MessageBoxIcon icon)
        {
            var dlg = new CustomMessageBox(message, title, buttons, icon);
            dlg.ShowDialog();
            return dlg._result;
        }
    }
}
