using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace AxCopilot.Views;

public partial class SettingsWindow
{
    // ─── 에이전트 훅 관리 ─────────────────────────────────────────────────

    private void AddHookBtn_Click(object sender, MouseButtonEventArgs e)
    {
        ShowHookEditDialog(null, -1);
    }

    /// <summary>플레이스홀더(워터마크) TextBlock 생성 헬퍼.</summary>
    private static TextBlock CreatePlaceholder(string text, Brush foreground, string? currentValue)
    {
        return new TextBlock
        {
            Text = text,
            FontSize = 13,
            Foreground = foreground,
            Opacity = 0.45,
            IsHitTestVisible = false,
            VerticalAlignment = VerticalAlignment.Center,
            Padding = new Thickness(14, 8, 14, 8),
            Visibility = string.IsNullOrEmpty(currentValue) ? Visibility.Visible : Visibility.Collapsed,
        };
    }

    private void ShowHookEditDialog(Models.AgentHookEntry? existing, int index)
    {
        var bgBrush = TryFindResource("LauncherBackground") as Brush ?? new SolidColorBrush(Color.FromRgb(0x1E, 0x1E, 0x2E));
        var fgBrush = TryFindResource("PrimaryText") as Brush ?? Brushes.White;
        var subFgBrush = TryFindResource("SecondaryText") as Brush ?? Brushes.Gray;
        var borderBrush = TryFindResource("BorderColor") as Brush ?? new SolidColorBrush(Color.FromRgb(0x40, 0x40, 0x60));
        var itemBg = TryFindResource("ItemBackground") as Brush ?? new SolidColorBrush(Color.FromRgb(0x2A, 0x2A, 0x40));
        var accentBrush = TryFindResource("AccentColor") as Brush ?? Brushes.CornflowerBlue;

        var isNew = existing == null;
        var dlg = new Window
        {
            Title = isNew ? "훅 추가" : "훅 편집",
            Width = 420, SizeToContent = SizeToContent.Height,
            WindowStartupLocation = WindowStartupLocation.CenterOwner,
            Owner = this, ResizeMode = ResizeMode.NoResize,
            WindowStyle = WindowStyle.None, AllowsTransparency = true,
            Background = Brushes.Transparent,
        };

        var border = new Border
        {
            Background = bgBrush, CornerRadius = new CornerRadius(12),
            BorderBrush = borderBrush, BorderThickness = new Thickness(1), Padding = new Thickness(20),
        };
        var stack = new StackPanel();

        // 제목
        stack.Children.Add(new TextBlock
        {
            Text = isNew ? "\u2699 훅 추가" : "\u2699 훅 편집",
            FontSize = 15, FontWeight = FontWeights.SemiBold,
            Foreground = fgBrush, Margin = new Thickness(0, 0, 0, 14),
        });

        // ESC 키로 닫기
        dlg.KeyDown += (_, e) => { if (e.Key == System.Windows.Input.Key.Escape) dlg.Close(); };

        // 훅 이름
        stack.Children.Add(new TextBlock { Text = "훅 이름", FontSize = 12, Foreground = subFgBrush, Margin = new Thickness(0, 0, 0, 4) });
        var nameBox = new TextBox
        {
            Text = existing?.Name ?? "", FontSize = 13,
            Foreground = fgBrush, Background = itemBg,
            BorderBrush = borderBrush, Padding = new Thickness(12, 8, 12, 8),
        };
        var nameHolder = CreatePlaceholder("예: 코드 리뷰 후 알림", subFgBrush, existing?.Name);
        nameBox.TextChanged += (_, _) => nameHolder.Visibility = string.IsNullOrEmpty(nameBox.Text) ? Visibility.Visible : Visibility.Collapsed;
        var nameGrid = new Grid();
        nameGrid.Children.Add(nameBox);
        nameGrid.Children.Add(nameHolder);
        stack.Children.Add(nameGrid);

        // 대상 도구
        stack.Children.Add(new TextBlock { Text = "대상 도구 (* = 모든 도구)", FontSize = 12, Foreground = subFgBrush, Margin = new Thickness(0, 10, 0, 4) });
        var toolBox = new TextBox
        {
            Text = existing?.ToolName ?? "*", FontSize = 13,
            Foreground = fgBrush, Background = itemBg,
            BorderBrush = borderBrush, Padding = new Thickness(12, 8, 12, 8),
        };
        var toolHolder = CreatePlaceholder("예: file_write, grep_tool", subFgBrush, existing?.ToolName ?? "*");
        toolBox.TextChanged += (_, _) => toolHolder.Visibility = string.IsNullOrEmpty(toolBox.Text) ? Visibility.Visible : Visibility.Collapsed;
        var toolGrid = new Grid();
        toolGrid.Children.Add(toolBox);
        toolGrid.Children.Add(toolHolder);
        stack.Children.Add(toolGrid);

        // 타이밍
        stack.Children.Add(new TextBlock { Text = "실행 타이밍", FontSize = 12, Foreground = subFgBrush, Margin = new Thickness(0, 10, 0, 4) });
        var timingPanel = new StackPanel { Orientation = Orientation.Horizontal };
        var preRadio = new RadioButton { Content = "Pre (실행 전)", Foreground = fgBrush, FontSize = 13, Margin = new Thickness(0, 0, 16, 0), IsChecked = (existing?.Timing ?? "post") == "pre" };
        var postRadio = new RadioButton { Content = "Post (실행 후)", Foreground = fgBrush, FontSize = 13, IsChecked = (existing?.Timing ?? "post") != "pre" };
        timingPanel.Children.Add(preRadio);
        timingPanel.Children.Add(postRadio);
        stack.Children.Add(timingPanel);

        // 스크립트 경로
        stack.Children.Add(new TextBlock { Text = "스크립트 경로 (.bat / .cmd / .ps1)", FontSize = 12, Foreground = subFgBrush, Margin = new Thickness(0, 10, 0, 4) });
        var pathGrid = new Grid();
        pathGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
        pathGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        var pathInnerGrid = new Grid();
        var pathBox = new TextBox
        {
            Text = existing?.ScriptPath ?? "", FontSize = 13,
            Foreground = fgBrush, Background = itemBg,
            BorderBrush = borderBrush, Padding = new Thickness(12, 8, 12, 8),
        };
        var pathHolder = CreatePlaceholder("예: C:\\scripts\\review-notify.bat", subFgBrush, existing?.ScriptPath);
        pathBox.TextChanged += (_, _) => pathHolder.Visibility = string.IsNullOrEmpty(pathBox.Text) ? Visibility.Visible : Visibility.Collapsed;
        pathInnerGrid.Children.Add(pathBox);
        pathInnerGrid.Children.Add(pathHolder);
        Grid.SetColumn(pathInnerGrid, 0);
        pathGrid.Children.Add(pathInnerGrid);

        var browseBtn = new Border
        {
            Background = itemBg, CornerRadius = new CornerRadius(6),
            Padding = new Thickness(10, 6, 10, 6), Margin = new Thickness(6, 0, 0, 0),
            Cursor = Cursors.Hand, VerticalAlignment = VerticalAlignment.Center,
        };
        browseBtn.Child = new TextBlock { Text = "...", FontSize = 13, Foreground = accentBrush };
        browseBtn.MouseLeftButtonUp += (_, _) =>
        {
            var ofd = new Microsoft.Win32.OpenFileDialog
            {
                Filter = "스크립트 파일|*.bat;*.cmd;*.ps1|모든 파일|*.*",
                Title = "훅 스크립트 선택",
            };
            if (ofd.ShowDialog() == true) pathBox.Text = ofd.FileName;
        };
        Grid.SetColumn(browseBtn, 1);
        pathGrid.Children.Add(browseBtn);
        stack.Children.Add(pathGrid);

        // 추가 인수
        stack.Children.Add(new TextBlock { Text = "추가 인수 (선택)", FontSize = 12, Foreground = subFgBrush, Margin = new Thickness(0, 10, 0, 4) });
        var argsBox = new TextBox
        {
            Text = existing?.Arguments ?? "", FontSize = 13,
            Foreground = fgBrush, Background = itemBg,
            BorderBrush = borderBrush, Padding = new Thickness(12, 8, 12, 8),
        };
        var argsHolder = CreatePlaceholder("예: --verbose --output log.txt", subFgBrush, existing?.Arguments);
        argsBox.TextChanged += (_, _) => argsHolder.Visibility = string.IsNullOrEmpty(argsBox.Text) ? Visibility.Visible : Visibility.Collapsed;
        var argsGrid = new Grid();
        argsGrid.Children.Add(argsBox);
        argsGrid.Children.Add(argsHolder);
        stack.Children.Add(argsGrid);

        // 버튼 행
        var btnRow = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right, Margin = new Thickness(0, 16, 0, 0) };
        var cancelBorder = new Border
        {
            Background = itemBg, CornerRadius = new CornerRadius(8),
            Padding = new Thickness(16, 8, 16, 8), Margin = new Thickness(0, 0, 8, 0), Cursor = Cursors.Hand,
        };
        cancelBorder.Child = new TextBlock { Text = "취소", FontSize = 13, Foreground = subFgBrush };
        cancelBorder.MouseLeftButtonUp += (_, _) => dlg.Close();
        btnRow.Children.Add(cancelBorder);

        var saveBorder = new Border
        {
            Background = accentBrush, CornerRadius = new CornerRadius(8),
            Padding = new Thickness(16, 8, 16, 8), Cursor = Cursors.Hand,
        };
        saveBorder.Child = new TextBlock { Text = isNew ? "추가" : "저장", FontSize = 13, Foreground = Brushes.White, FontWeight = FontWeights.SemiBold };
        saveBorder.MouseLeftButtonUp += (_, _) =>
        {
            if (string.IsNullOrWhiteSpace(nameBox.Text) || string.IsNullOrWhiteSpace(pathBox.Text))
            {
                CustomMessageBox.Show("훅 이름과 스크립트 경로를 입력하세요.", "입력 오류", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            var entry = new Models.AgentHookEntry
            {
                Name = nameBox.Text.Trim(),
                ToolName = string.IsNullOrWhiteSpace(toolBox.Text) ? "*" : toolBox.Text.Trim(),
                Timing = preRadio.IsChecked == true ? "pre" : "post",
                ScriptPath = pathBox.Text.Trim(),
                Arguments = argsBox.Text.Trim(),
                Enabled = existing?.Enabled ?? true,
            };

            var hooks = _vm.Service.Settings.Llm.AgentHooks;
            if (isNew)
                hooks.Add(entry);
            else if (index >= 0 && index < hooks.Count)
                hooks[index] = entry;

            BuildHookCards();
            dlg.Close();
        };
        btnRow.Children.Add(saveBorder);
        stack.Children.Add(btnRow);

        border.Child = stack;
        dlg.Content = border;
        dlg.ShowDialog();
    }

    private void BuildHookCards()
    {
        if (HookListPanel == null) return;
        HookListPanel.Children.Clear();

        var hooks = _vm.Service.Settings.Llm.AgentHooks;
        var primaryText = TryFindResource("PrimaryText") as Brush ?? Brushes.Black;
        var secondaryText = TryFindResource("SecondaryText") as Brush ?? Brushes.Gray;
        var accentBrush = TryFindResource("AccentColor") as Brush ?? Brushes.Blue;

        for (int i = 0; i < hooks.Count; i++)
        {
            var hook = hooks[i];
            var idx = i;

            var card = new Border
            {
                Background = TryFindResource("ItemBackground") as Brush ?? Brushes.LightGray,
                CornerRadius = new CornerRadius(8), Padding = new Thickness(10, 8, 10, 8),
                Margin = new Thickness(0, 0, 0, 4),
            };

            var grid = new Grid();
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });   // 토글
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); // 정보
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });   // 편집
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });   // 삭제

            // 토글
            var toggle = new CheckBox
            {
                IsChecked = hook.Enabled,
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(0, 0, 8, 0),
                Style = TryFindResource("ToggleSwitch") as Style,
            };
            var capturedHook = hook;
            toggle.Checked += (_, _) => capturedHook.Enabled = true;
            toggle.Unchecked += (_, _) => capturedHook.Enabled = false;
            Grid.SetColumn(toggle, 0);
            grid.Children.Add(toggle);

            // 정보
            var info = new StackPanel { VerticalAlignment = VerticalAlignment.Center };
            var timingBadge = hook.Timing == "pre" ? "PRE" : "POST";
            var timingColor = hook.Timing == "pre" ? "#FF9800" : "#4CAF50";
            var headerPanel = new StackPanel { Orientation = Orientation.Horizontal };
            headerPanel.Children.Add(new TextBlock
            {
                Text = hook.Name, FontSize = 13, FontWeight = FontWeights.SemiBold,
                Foreground = primaryText, VerticalAlignment = VerticalAlignment.Center,
            });
            headerPanel.Children.Add(new Border
            {
                Background = ThemeResourceHelper.HexBrush(timingColor),
                CornerRadius = new CornerRadius(4), Padding = new Thickness(5, 1, 5, 1),
                Margin = new Thickness(6, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center,
                Child = new TextBlock { Text = timingBadge, FontSize = 9, Foreground = Brushes.White, FontWeight = FontWeights.Bold },
            });
            if (hook.ToolName != "*")
            {
                headerPanel.Children.Add(new Border
                {
                    Background = new SolidColorBrush(Color.FromArgb(40, 100, 100, 255)),
                    CornerRadius = new CornerRadius(4), Padding = new Thickness(5, 1, 5, 1),
                    Margin = new Thickness(4, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center,
                    Child = new TextBlock { Text = hook.ToolName, FontSize = 9, Foreground = accentBrush },
                });
            }
            info.Children.Add(headerPanel);
            info.Children.Add(new TextBlock
            {
                Text = System.IO.Path.GetFileName(hook.ScriptPath),
                FontSize = 11, Foreground = secondaryText,
                TextTrimming = TextTrimming.CharacterEllipsis, MaxWidth = 200,
            });
            Grid.SetColumn(info, 1);
            grid.Children.Add(info);

            // 편집 버튼
            var editBtn = new Border
            {
                Cursor = Cursors.Hand, VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(4, 0, 4, 0), Padding = new Thickness(6),
            };
            editBtn.Child = new TextBlock
            {
                Text = "\uE70F", FontFamily = ThemeResourceHelper.SegoeMdl2,
                FontSize = 12, Foreground = secondaryText,
            };
            editBtn.MouseLeftButtonUp += (_, _) => ShowHookEditDialog(hooks[idx], idx);
            Grid.SetColumn(editBtn, 2);
            grid.Children.Add(editBtn);

            // 삭제 버튼
            var delBtn = new Border
            {
                Cursor = Cursors.Hand, VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(0, 0, 0, 0), Padding = new Thickness(6),
            };
            delBtn.Child = new TextBlock
            {
                Text = "\uE74D", FontFamily = ThemeResourceHelper.SegoeMdl2,
                FontSize = 12, Foreground = new SolidColorBrush(Color.FromRgb(0xEF, 0x53, 0x50)),
            };
            delBtn.MouseLeftButtonUp += (_, _) =>
            {
                hooks.RemoveAt(idx);
                BuildHookCards();
            };
            Grid.SetColumn(delBtn, 3);
            grid.Children.Add(delBtn);

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