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

namespace AxCopilot.Views;

public partial class SettingsWindow
{
    // ─── 저장 공간 관리 ──────────────────────────────────────────────────────

    private void RefreshStorageInfo()
    {
        if (StorageSummaryText == null) return;
        var report = StorageAnalyzer.Analyze();

        StorageSummaryText.Text = $"앱 전체 사용량: {StorageAnalyzer.FormatSize(report.TotalAppUsage)}";
        StorageDriveText.Text = $"드라이브 {report.DriveLabel} 여유: {StorageAnalyzer.FormatSize(report.DriveFreeSpace)} / {StorageAnalyzer.FormatSize(report.DriveTotalSpace)}";

        if (StorageDetailPanel == null) return;
        StorageDetailPanel.Children.Clear();

        var items = new (string Label, long Size)[]
        {
            ("대화 기록", report.Conversations),
            ("감사 로그", report.AuditLogs),
            ("앱 로그", report.Logs),
            ("코드 인덱스", report.CodeIndex),
            ("임베딩 DB", report.EmbeddingDb),
            ("클립보드 히스토리", report.ClipboardHistory),
            ("플러그인", report.Plugins),
            ("JSON 스킬", report.Skills),
        };

        foreach (var (label, size) in items)
        {
            if (size == 0) continue;
            var row = new Grid { Margin = new Thickness(0, 2, 0, 2) };
            row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });

            var labelTb = new TextBlock { Text = label, FontSize = 12, Foreground = TryFindResource("PrimaryText") as Brush ?? Brushes.Black, VerticalAlignment = VerticalAlignment.Center };
            Grid.SetColumn(labelTb, 0);
            row.Children.Add(labelTb);

            var sizeTb = new TextBlock { Text = StorageAnalyzer.FormatSize(size), FontSize = 12, FontFamily = ThemeResourceHelper.Consolas, Foreground = Brushes.Gray, VerticalAlignment = VerticalAlignment.Center };
            Grid.SetColumn(sizeTb, 1);
            row.Children.Add(sizeTb);

            StorageDetailPanel.Children.Add(row);
        }
    }

    private void BtnStorageRefresh_Click(object sender, RoutedEventArgs e) => RefreshStorageInfo();

    private void RefreshStorageInfo2()
    {
        if (StorageSummaryText2 == null) return;
        var report = StorageAnalyzer.Analyze();
        StorageSummaryText2.Text = $"앱 전체 사용량: {StorageAnalyzer.FormatSize(report.TotalAppUsage)}";
        StorageDriveText2.Text = $"드라이브 {report.DriveLabel} 여유: {StorageAnalyzer.FormatSize(report.DriveFreeSpace)} / {StorageAnalyzer.FormatSize(report.DriveTotalSpace)}";

        if (StorageDetailPanel2 == null) return;
        StorageDetailPanel2.Children.Clear();
        var items = new (string Label, long Size)[]
        {
            ("대화 기록", report.Conversations), ("감사 로그", report.AuditLogs),
            ("앱 로그", report.Logs), ("코드 인덱스", report.CodeIndex),
            ("임베딩 DB", report.EmbeddingDb),
            ("클립보드 히스토리", report.ClipboardHistory),
            ("플러그인", report.Plugins), ("JSON 스킬", report.Skills),
        };
        foreach (var (label, size) in items)
        {
            if (size == 0) continue;
            var row = new Grid { Margin = new Thickness(0, 2, 0, 2) };
            row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
            var labelTb = new TextBlock { Text = label, FontSize = 12, Foreground = TryFindResource("PrimaryText") as Brush ?? Brushes.Black };
            Grid.SetColumn(labelTb, 0); row.Children.Add(labelTb);
            var sizeTb = new TextBlock { Text = StorageAnalyzer.FormatSize(size), FontSize = 12, FontFamily = ThemeResourceHelper.Consolas, Foreground = Brushes.Gray };
            Grid.SetColumn(sizeTb, 1); row.Children.Add(sizeTb);
            StorageDetailPanel2.Children.Add(row);
        }
    }

    private void BtnStorageRefresh2_Click(object sender, RoutedEventArgs e) => RefreshStorageInfo2();

    private void BtnStorageCleanup_Click(object sender, RoutedEventArgs e)
    {
        // 테마 리소스 조회
        var bgBrush = TryFindResource("LauncherBackground") as Brush ?? new SolidColorBrush(Color.FromRgb(0x1A, 0x1B, 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(0x4B, 0x5E, 0xFC));
        var itemBg = TryFindResource("ItemBackground") as Brush ?? new SolidColorBrush(Color.FromArgb(0x10, 0xFF, 0xFF, 0xFF));
        var hoverBg = TryFindResource("ItemHoverBackground") as Brush ?? new SolidColorBrush(Color.FromArgb(0x22, 0xFF, 0xFF, 0xFF));
        var shadowColor = TryFindResource("ShadowColor") is Color sc ? sc : Colors.Black;

        // 보관 기간 선택 팝업 — 커스텀 버튼으로 날짜 선택
        var popup = new Window
        {
            WindowStyle = WindowStyle.None, AllowsTransparency = true, Background = Brushes.Transparent,
            Width = 360, SizeToContent = SizeToContent.Height,
            WindowStartupLocation = WindowStartupLocation.CenterOwner,
            Owner = this, ShowInTaskbar = false, Topmost = true,
        };

        int selectedDays = -1;

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

        var stack = new StackPanel { Margin = new Thickness(24, 20, 24, 20) };
        stack.Children.Add(new TextBlock { Text = "보관 기간 선택", FontSize = 15, FontWeight = FontWeights.SemiBold, Foreground = fgBrush, Margin = new Thickness(0, 0, 0, 6) });
        stack.Children.Add(new TextBlock { Text = "선택한 기간 이전의 데이터를 삭제합니다.\n※ 통계/대화 기록은 삭제되지 않습니다.", FontSize = 12, Foreground = subFgBrush, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 0, 0, 16) });

        var btnDays = new (int Days, string Label)[] { (7, "최근 7일만 보관"), (14, "최근 14일만 보관"), (30, "최근 30일만 보관"), (0, "전체 삭제") };
        foreach (var (days, label) in btnDays)
        {
            var d = days;
            var isDelete = d == 0;
            var deleteBg = new SolidColorBrush(Color.FromArgb(0x18, 0xFF, 0x44, 0x44));
            var deleteBorder = new SolidColorBrush(Color.FromArgb(0x40, 0xFF, 0x44, 0x44));
            var deleteText = new SolidColorBrush(Color.FromRgb(0xFF, 0x66, 0x66));
            var btn = new Border
            {
                CornerRadius = new CornerRadius(10), Cursor = Cursors.Hand,
                Padding = new Thickness(14, 10, 14, 10), Margin = new Thickness(0, 0, 0, 6),
                Background = isDelete ? deleteBg : itemBg,
                BorderBrush = isDelete ? deleteBorder : borderBrush,
                BorderThickness = new Thickness(1),
            };
            btn.Child = new TextBlock { Text = label, FontSize = 13, Foreground = isDelete ? deleteText : fgBrush };
            var normalBg = isDelete ? deleteBg : itemBg;
            btn.MouseEnter += (s, _) => { if (s is Border b) b.Background = hoverBg; };
            btn.MouseLeave += (s, _) => { if (s is Border b) b.Background = normalBg; };
            btn.MouseLeftButtonUp += (_, _) => { selectedDays = d; popup.Close(); };
            stack.Children.Add(btn);
        }

        // 취소
        var cancelBtn = new Border { CornerRadius = new CornerRadius(10), Cursor = Cursors.Hand, Padding = new Thickness(14, 8, 14, 8), Margin = new Thickness(0, 6, 0, 0), Background = Brushes.Transparent };
        cancelBtn.Child = new TextBlock { Text = "취소", FontSize = 12, Foreground = subFgBrush, HorizontalAlignment = HorizontalAlignment.Center };
        cancelBtn.MouseLeftButtonUp += (_, _) => popup.Close();
        stack.Children.Add(cancelBtn);

        outerBorder.Child = stack;
        popup.Content = outerBorder;
        popup.ShowDialog();

        if (selectedDays < 0) return;

        // 삭제 전 확인
        var confirmMsg = selectedDays == 0
            ? "전체 데이터를 삭제합니다. 정말 진행하시겠습니까?"
            : $"최근 {selectedDays}일 이전의 데이터를 삭제합니다. 정말 진행하시겠습니까?";
        var confirm = CustomMessageBox.Show(confirmMsg, "삭제 확인", MessageBoxButton.YesNo, MessageBoxImage.Warning);
        if (confirm != MessageBoxResult.Yes) return;

        var freed = StorageAnalyzer.Cleanup(
            retainDays: selectedDays,
            cleanConversations: false,
            cleanAuditLogs: true,
            cleanLogs: true,
            cleanCodeIndex: true,
            cleanClipboard: selectedDays == 0
        );

        CustomMessageBox.Show(
            $"{StorageAnalyzer.FormatSize(freed)}를 확보했습니다.",
            "정리 완료", MessageBoxButton.OK, MessageBoxImage.Information);

        RefreshStorageInfo();
    }
}
