using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using AxCopilot.Services.Agent;
using AxCopilot.ViewModels;
using Microsoft.Win32;

namespace AxCopilot.Views;

/// <summary>
/// Phase 18-C1: SettingsWindow — 플러그인 갤러리 탭.
/// PluginGalleryViewModel을 코드비하인드에서 바인딩하여 플러그인 설치·관리를 지원합니다.
/// </summary>
public partial class SettingsWindow
{
    private PluginGalleryViewModel? _pluginVm;

    // ─── 초기화 ──────────────────────────────────────────────────────────────

    private void InitPluginGallery()
    {
        if (_pluginVm != null) return;
        var installService = new PluginInstallService();
        _pluginVm = new PluginGalleryViewModel(installService);
        _pluginVm.Refresh();
        RenderPluginList();
    }

    // ─── 버튼 이벤트 ─────────────────────────────────────────────────────────

    private async void BtnInstallPlugin_Click(object sender, MouseButtonEventArgs e)
    {
        var dlg = new OpenFileDialog
        {
            Title = "플러그인 zip 파일 선택",
            Filter = "플러그인 패키지 (*.zip)|*.zip",
            InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
        };

        if (dlg.ShowDialog() != true) return;

        PluginStatusText.Text = "설치 중...";
        BtnInstallPlugin.IsEnabled = false;

        try
        {
            var svc = new PluginInstallService();
            var result = await svc.InstallFromZipAsync(dlg.FileName);
            PluginStatusText.Text = result.Success
                ? $"✓ {result.Message}"
                : $"✗ {result.Message}";

            if (result.Success)
            {
                _pluginVm?.Refresh();
                RenderPluginList();
            }
        }
        finally
        {
            BtnInstallPlugin.IsEnabled = true;
        }
    }

    private void BtnRefreshPlugins_Click(object sender, MouseButtonEventArgs e)
    {
        _pluginVm?.Refresh();
        RenderPluginList();
        PluginStatusText.Text = "새로고침 완료";
    }

    // ─── 플러그인 목록 렌더링 ──────────────────────────────────────────────────

    private void RenderPluginList()
    {
        if (_pluginVm == null || PluginListPanel == null) return;
        PluginListPanel.Children.Clear();

        var primaryText   = TryFindResource("PrimaryText")   as Brush ?? Brushes.White;
        var secondaryText = TryFindResource("SecondaryText") as Brush ?? Brushes.Gray;
        var itemBg        = TryFindResource("ItemBackground") as Brush
                            ?? new SolidColorBrush(Color.FromArgb(0x15, 0xFF, 0xFF, 0xFF));
        var hoverBg       = TryFindResource("ItemHoverBackground") as Brush
                            ?? new SolidColorBrush(Color.FromArgb(0x20, 0xFF, 0xFF, 0xFF));
        var accentColor   = TryFindResource("AccentColor") as Brush ?? Brushes.CornflowerBlue;

        if (_pluginVm.Plugins.Count == 0)
        {
            PluginListPanel.Children.Add(new TextBlock
            {
                Text = "설치된 플러그인이 없습니다.\n'zip에서 설치' 버튼으로 플러그인을 추가하세요.",
                FontSize = 12,
                Foreground = secondaryText,
                TextWrapping = System.Windows.TextWrapping.Wrap,
                Margin = new Thickness(0, 8, 0, 8),
                LineHeight = 20,
            });
            return;
        }

        foreach (var plugin in _pluginVm.Plugins)
        {
            var card = new Border
            {
                Background   = itemBg,
                CornerRadius = new CornerRadius(10),
                Padding      = new Thickness(16, 12, 16, 12),
                Margin       = new Thickness(0, 0, 0, 8),
            };

            var grid = new Grid();
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });

            // 왼쪽: 플러그인 정보
            var infoStack = new StackPanel();

            // 이름 + 유형 배지
            var nameRow = new StackPanel { Orientation = Orientation.Horizontal };
            nameRow.Children.Add(new TextBlock
            {
                Text       = plugin.Name,
                FontSize   = 13,
                FontWeight = FontWeights.SemiBold,
                Foreground = primaryText,
            });
            var typeBadge = new Border
            {
                Background   = GetTypeBadgeColor(plugin.Type),
                CornerRadius = new CornerRadius(4),
                Padding      = new Thickness(6, 2, 6, 2),
                Margin       = new Thickness(8, 0, 0, 0),
                VerticalAlignment = VerticalAlignment.Center,
            };
            typeBadge.Child = new TextBlock
            {
                Text       = plugin.Type,
                FontSize   = 10,
                Foreground = Brushes.White,
                FontWeight = FontWeights.SemiBold,
            };
            nameRow.Children.Add(typeBadge);
            infoStack.Children.Add(nameRow);

            infoStack.Children.Add(new TextBlock
            {
                Text       = plugin.Description,
                FontSize   = 11,
                Foreground = secondaryText,
                Margin     = new Thickness(0, 4, 0, 4),
                TextWrapping = System.Windows.TextWrapping.Wrap,
            });

            infoStack.Children.Add(new TextBlock
            {
                Text       = $"v{plugin.Version}  |  {plugin.Author}  |  설치일: {plugin.InstalledAt}",
                FontSize   = 10,
                Foreground = secondaryText,
            });

            Grid.SetColumn(infoStack, 0);
            grid.Children.Add(infoStack);

            // 오른쪽: 활성화 토글 + 제거
            var actionStack = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                VerticalAlignment = VerticalAlignment.Center,
            };

            // 활성화 토글
            var isEnabled = plugin.IsEnabled;
            var toggleBorder = new Border
            {
                Width = 40, Height = 22, CornerRadius = new CornerRadius(11),
                Background = isEnabled ? accentColor : itemBg,
                BorderBrush = secondaryText, BorderThickness = new Thickness(1),
                Cursor = Cursors.Hand,
                Margin = new Thickness(0, 0, 10, 0),
                Tag = plugin,
            };
            var toggleThumb = new Border
            {
                Width = 16, Height = 16, CornerRadius = new CornerRadius(8),
                Background = Brushes.White,
                HorizontalAlignment = isEnabled ? HorizontalAlignment.Right : HorizontalAlignment.Left,
                Margin = new Thickness(3),
            };
            toggleBorder.Child = toggleThumb;
            var capturedPlugin = plugin;
            toggleBorder.MouseLeftButtonUp += async (_, _) =>
            {
                capturedPlugin.IsEnabled = !capturedPlugin.IsEnabled;
                var svc = new PluginInstallService();
                await svc.SetEnabledAsync(capturedPlugin.Id, capturedPlugin.IsEnabled);
                RenderPluginList();  // 재렌더링
            };
            actionStack.Children.Add(toggleBorder);

            // 제거 버튼
            var removeBorder = new Border
            {
                Width = 28, Height = 28, CornerRadius = new CornerRadius(6),
                Background = Brushes.Transparent, Cursor = Cursors.Hand,
            };
            removeBorder.Child = new TextBlock
            {
                Text = "\uE74D", FontFamily = ThemeResourceHelper.SegoeMdl2, FontSize = 13,
                Foreground = new SolidColorBrush(Color.FromRgb(0xF8, 0x71, 0x71)),
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center,
            };
            removeBorder.MouseEnter  += (_, _) => removeBorder.Background = hoverBg;
            removeBorder.MouseLeave  += (_, _) => removeBorder.Background = Brushes.Transparent;
            removeBorder.MouseLeftButtonUp += async (_, _) =>
            {
                var confirm = CustomMessageBox.Show(
                    $"'{capturedPlugin.Name}' 플러그인을 제거하시겠습니까?",
                    "플러그인 제거",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question);

                if (confirm != MessageBoxResult.Yes) return;

                var svc = new PluginInstallService();
                await svc.UninstallAsync(capturedPlugin.Id);
                _pluginVm?.Refresh();
                RenderPluginList();
                PluginStatusText.Text = $"'{capturedPlugin.Name}' 제거 완료";
            };
            actionStack.Children.Add(removeBorder);

            Grid.SetColumn(actionStack, 1);
            grid.Children.Add(actionStack);

            card.Child = grid;
            PluginListPanel.Children.Add(card);
        }
    }

    private static Brush GetTypeBadgeColor(string type) => type?.ToLowerInvariant() switch
    {
        "skill"  => new SolidColorBrush(Color.FromRgb(0x60, 0xA5, 0xFA)),
        "tool"   => new SolidColorBrush(Color.FromRgb(0x34, 0xD3, 0x99)),
        "theme"  => new SolidColorBrush(Color.FromRgb(0xFB, 0xBF, 0x24)),
        _        => new SolidColorBrush(Color.FromRgb(0x94, 0xA3, 0xB8)),
    };
}
