using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using AxCopilot.Services;
using AxCopilot.Services.Agent;

namespace AxCopilot.Views;

public partial class SkillEditorWindow
{
    // ─── 미리보기 + 저장 + 편집 모드 로드 ────────────────────────────────────

    private void BtnPreview_Click(object sender, MouseButtonEventArgs e)
    {
        var content = GenerateSkillContent();

        var previewWin = new Window
        {
            Title                = "스킬 파일 미리보기",
            Width                = 640,
            Height               = 520,
            WindowStyle          = WindowStyle.None,
            AllowsTransparency   = true,
            Background           = Brushes.Transparent,
            WindowStartupLocation = WindowStartupLocation.CenterOwner,
            Owner                = this,
        };

        var bgBrush = TryFindResource("LauncherBackground") as Brush ?? Brushes.White;
        var fgBrush = TryFindResource("PrimaryText") as Brush ?? Brushes.White;
        var subBrush = TryFindResource("SecondaryText") as Brush ?? Brushes.Gray;
        var itemBg = TryFindResource("ItemBackground") as Brush ?? Brushes.Transparent;
        var borderBrush = TryFindResource("BorderColor") as Brush ?? Brushes.Gray;

        var outerBorder = new Border
        {
            Background   = bgBrush,
            CornerRadius = new CornerRadius(12),
            BorderBrush  = borderBrush,
            BorderThickness = new Thickness(1),
            Effect       = new System.Windows.Media.Effects.DropShadowEffect
            {
                BlurRadius = 20, ShadowDepth = 4, Opacity = 0.3, Color = Colors.Black,
            },
        };

        var grid = new Grid();
        grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(44) });
        grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
        grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

        // 타이틀바
        var titleBar = new Border
        {
            Background   = itemBg,
            CornerRadius = new CornerRadius(12, 12, 0, 0),
        };
        titleBar.MouseLeftButtonDown += (_, _) => previewWin.DragMove();
        var titleText = new TextBlock
        {
            Text              = "미리보기 — .skill.md",
            FontSize          = 14,
            FontWeight        = FontWeights.SemiBold,
            Foreground        = fgBrush,
            VerticalAlignment = VerticalAlignment.Center,
            Margin            = new Thickness(16, 0, 0, 0),
        };
        titleBar.Child = titleText;
        Grid.SetRow(titleBar, 0);

        // 콘텐츠
        var textBox = new TextBox
        {
            Text                        = content,
            FontFamily                  = ThemeResourceHelper.ConsolasCode,
            FontSize                    = 12.5,
            IsReadOnly                  = true,
            AcceptsReturn               = true,
            TextWrapping                = TextWrapping.Wrap,
            VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
            Background                  = itemBg,
            Foreground                  = fgBrush,
            BorderThickness             = new Thickness(0),
            Padding                     = new Thickness(16, 12, 16, 12),
            Margin                      = new Thickness(8, 8, 8, 0),
        };
        Grid.SetRow(textBox, 1);

        // 하단
        var bottomBar = new Border
        {
            Padding         = new Thickness(16, 10, 16, 10),
            CornerRadius    = new CornerRadius(0, 0, 12, 12),
        };
        var closeBtn = new Border
        {
            CornerRadius         = new CornerRadius(8),
            Padding              = new Thickness(18, 8, 18, 8),
            Background           = itemBg,
            Cursor               = Cursors.Hand,
            HorizontalAlignment  = HorizontalAlignment.Right,
        };
        closeBtn.Child = new TextBlock
        {
            Text       = "닫기",
            FontSize   = 12.5,
            Foreground = subBrush,
        };
        closeBtn.MouseLeftButtonUp += (_, _) => previewWin.Close();
        closeBtn.MouseEnter += (s, _) =>
        {
            if (s is Border b) b.Background = new SolidColorBrush(Color.FromArgb(0x18, 0xFF, 0xFF, 0xFF));
        };
        closeBtn.MouseLeave += (s, _) =>
        {
            if (s is Border b) b.Background = itemBg;
        };
        bottomBar.Child = closeBtn;
        Grid.SetRow(bottomBar, 2);

        grid.Children.Add(titleBar);
        grid.Children.Add(textBox);
        grid.Children.Add(bottomBar);
        outerBorder.Child = grid;
        previewWin.Content = outerBorder;
        previewWin.ShowDialog();
    }

    // ─── 저장 ─────────────────────────────────────────────────────────────

    private void BtnSave_Click(object sender, MouseButtonEventArgs e)
    {
        // 유효성 검사
        var name = TxtName.Text.Trim();
        if (string.IsNullOrWhiteSpace(name))
        {
            StatusText.Text = "⚠ 이름을 입력하세요.";
            StatusText.Foreground = new SolidColorBrush(Color.FromRgb(0xF8, 0x71, 0x71));
            TxtName.Focus();
            return;
        }

        // 영문 + 하이픈 + 숫자만 허용
        if (!System.Text.RegularExpressions.Regex.IsMatch(name, @"^[a-zA-Z][a-zA-Z0-9\-]*$"))
        {
            StatusText.Text = "⚠ 이름은 영문으로 시작하며 영문, 숫자, 하이픈만 사용 가능합니다.";
            StatusText.Foreground = new SolidColorBrush(Color.FromRgb(0xF8, 0x71, 0x71));
            TxtName.Focus();
            return;
        }

        if (string.IsNullOrWhiteSpace(TxtInstructions.Text))
        {
            StatusText.Text = "⚠ 지시사항을 입력하세요.";
            StatusText.Foreground = new SolidColorBrush(Color.FromRgb(0xF8, 0x71, 0x71));
            TxtInstructions.Focus();
            return;
        }

        var content = GenerateSkillContent();

        // 저장 경로 결정
        string savePath;
        if (_editingSkill != null)
        {
            // 편집 모드: 기존 파일 덮어쓰기
            savePath = _editingSkill.FilePath;
        }
        else
        {
            // 새 스킬: 사용자 폴더에 저장
            var userFolder = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                "AxCopilot", "skills");
            if (!Directory.Exists(userFolder))
                Directory.CreateDirectory(userFolder);

            savePath = Path.Combine(userFolder, $"{name}.skill.md");

            // 파일 이름 충돌 시 숫자 추가
            if (File.Exists(savePath))
            {
                var counter = 2;
                while (File.Exists(Path.Combine(userFolder, $"{name}_{counter}.skill.md")))
                    counter++;
                savePath = Path.Combine(userFolder, $"{name}_{counter}.skill.md");
            }
        }

        try
        {
            File.WriteAllText(savePath, content, System.Text.Encoding.UTF8);
            SkillService.LoadSkills();

            StatusText.Text = $"✓ 저장 완료: {Path.GetFileName(savePath)}";
            StatusText.Foreground = new SolidColorBrush(Color.FromRgb(0x34, 0xD3, 0x99));

            // 편집 결과 반환
            DialogResult = true;
        }
        catch (Exception ex)
        {
            CustomMessageBox.Show($"저장 실패: {ex.Message}", "스킬 저장");
        }
    }

    // ─── 편집 모드 로드 ───────────────────────────────────────────────────

    private void LoadSkill(SkillDefinition skill)
    {
        TitleText.Text = "스킬 편집";
        TxtName.Text = skill.Name;
        TxtLabel.Text = skill.Label;
        TxtDescription.Text = skill.Description;
        TxtInstructions.Text = skill.SystemPrompt;

        // 아이콘 선택
        _selectedIcon = IconCandidates.Contains(skill.Icon) ? skill.Icon : IconCandidates[0];
        BuildIconSelector();

        // 런타임 요구사항
        for (int i = 0; i < CmbRequires.Items.Count; i++)
        {
            if (CmbRequires.Items[i] is ComboBoxItem item
                && item.Tag is string tag
                && string.Equals(tag, skill.Requires, StringComparison.OrdinalIgnoreCase))
            {
                CmbRequires.SelectedIndex = i;
                break;
            }
        }

        // 도구 체크리스트 (BuildToolChecklist에서 이미 _editingSkill 기반으로 설정됨)
        UpdatePreview();
    }
}
