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

namespace AxCopilot.Views;

public partial class SettingsWindow
{
    // ─── 접기/열기 가능 섹션 헬퍼 ──────────────────────────────────────────
    private Border CreateCollapsibleSection(string title, UIElement content, bool expanded = true)
    {
        var headerColor = ThemeResourceHelper.HexBrush("#AAAACC");
        var section = new StackPanel();
        var contentPanel = new StackPanel { Visibility = expanded ? Visibility.Visible : Visibility.Collapsed };
        if (content is Panel panel)
        {
            // 패널의 자식들을 contentPanel로 옮김 (StackPanel 등)
            contentPanel.Children.Add(content);
        }
        else
        {
            contentPanel.Children.Add(content);
        }

        var arrow = new TextBlock
        {
            Text = "\uE70D",
            FontFamily = ThemeResourceHelper.SegoeMdl2,
            FontSize = 9,
            Foreground = headerColor,
            VerticalAlignment = VerticalAlignment.Center,
            Margin = new Thickness(0, 0, 6, 0),
            RenderTransformOrigin = new Point(0.5, 0.5),
            RenderTransform = new RotateTransform(expanded ? 90 : 0),
        };
        var titleBlock = new TextBlock
        {
            Text = title,
            FontSize = 10.5,
            FontWeight = FontWeights.SemiBold,
            Foreground = headerColor,
            VerticalAlignment = VerticalAlignment.Center,
        };
        var headerPanel = new StackPanel { Orientation = Orientation.Horizontal };
        headerPanel.Children.Add(arrow);
        headerPanel.Children.Add(titleBlock);

        var header = new Border
        {
            Background = Brushes.Transparent,
            Cursor = Cursors.Hand,
            Padding = new Thickness(2, 10, 2, 6),
            Child = headerPanel,
        };
        header.MouseLeftButtonUp += (s, e) =>
        {
            bool isNowVisible = contentPanel.Visibility == Visibility.Visible;
            contentPanel.Visibility = isNowVisible ? Visibility.Collapsed : Visibility.Visible;
            arrow.RenderTransform = new RotateTransform(isNowVisible ? 0 : 90);
        };
        header.MouseEnter += (s, _) => titleBlock.Foreground = ThemeResourceHelper.HexBrush("#CCCCEE");
        header.MouseLeave += (s, _) => titleBlock.Foreground = headerColor;

        section.Children.Add(header);
        section.Children.Add(contentPanel);

        return new Border
        {
            Child = section,
            Margin = new Thickness(0, 2, 0, 0),
        };
    }

    private Border CreateCollapsibleSection(string title, IEnumerable<UIElement> children, bool expanded = true)
    {
        var contentPanel = new StackPanel();
        foreach (var child in children)
            contentPanel.Children.Add(child);
        return CreateCollapsibleSection(title, contentPanel, expanded);
    }

    // ─── 선택 텍스트 AI 명령 설정 ────────────────────────────────────────────────

    private void BuildTextActionCommandsPanel()
    {
        if (TextActionCommandsPanel == null) return;
        TextActionCommandsPanel.Children.Clear();

        var svc = CurrentApp?.SettingsService;
        if (svc == null) return;
        var enabled = svc.Settings.Launcher.TextActionCommands;
        var toggleStyle = TryFindResource("ToggleSwitch") as Style;

        foreach (var (key, label) in TextActionPopup.AvailableCommands)
        {
            var row = new Grid { Margin = new Thickness(0, 3, 0, 3) };
            row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });

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

            var capturedKey = key;
            var cb = new CheckBox
            {
                IsChecked = enabled.Contains(key, StringComparer.OrdinalIgnoreCase),
                HorizontalAlignment = HorizontalAlignment.Right,
                VerticalAlignment = VerticalAlignment.Center,
            };
            if (toggleStyle != null) cb.Style = toggleStyle;
            cb.Checked += (_, _) =>
            {
                if (!enabled.Contains(capturedKey)) enabled.Add(capturedKey);
                svc.Save();
            };
            cb.Unchecked += (_, _) =>
            {
                // 최소 1개 유지
                if (enabled.Count <= 1) { cb.IsChecked = true; return; }
                enabled.RemoveAll(x => x == capturedKey);
                svc.Save();
            };
            Grid.SetColumn(cb, 1);
            row.Children.Add(cb);

            TextActionCommandsPanel.Children.Add(row);
        }
    }

    // ─── 테마 하위 탭 전환 ──────────────────────────────────────────────────────

    private void ThemeSubTab_Checked(object sender, RoutedEventArgs e)
    {
        if (ThemeSelectPanel == null || ThemeColorsPanel == null) return;
        if (ThemeSubTabSelect?.IsChecked == true)
        {
            ThemeSelectPanel.Visibility = Visibility.Visible;
            ThemeColorsPanel.Visibility = Visibility.Collapsed;
        }
        else
        {
            ThemeSelectPanel.Visibility = Visibility.Collapsed;
            ThemeColorsPanel.Visibility = Visibility.Visible;
        }
    }

    // ─── 일반 하위 탭 전환 (일반 + 알림) ──────────────────────────────────────

    private bool _notifyMoved;

    private void GeneralSubTab_Checked(object sender, RoutedEventArgs e)
    {
        if (GeneralMainPanel == null || GeneralNotifyPanel == null) return;

        // 알림 탭 내용을 최초 1회 NotifyContent로 이동
        if (!_notifyMoved && NotifyContent != null)
        {
            MoveNotifyTabContent();
            _notifyMoved = true;
        }

        GeneralMainPanel.Visibility = GeneralSubTabMain?.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
        GeneralNotifyPanel.Visibility = GeneralSubTabNotify?.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
        if (GeneralStoragePanel != null)
        {
            GeneralStoragePanel.Visibility = GeneralSubTabStorage?.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
            if (GeneralSubTabStorage?.IsChecked == true) RefreshStorageInfo2();
        }
    }

    private void MoveNotifyTabContent()
    {
        // XAML의 알림 TabItem에서 ScrollViewer → StackPanel 내용을 NotifyContent로 이동
        // 사이드 네비의 "알림" 탭을 찾아서 숨기기
        var mainTab = Content as System.Windows.Controls.Grid;
        var tabControl = mainTab?.Children.OfType<TabControl>().FirstOrDefault()
                         ?? FindVisualChild<TabControl>(this);
        if (tabControl == null) return;

        TabItem? notifyTab = null;
        foreach (TabItem tab in tabControl.Items)
        {
            if (tab.Header?.ToString() == "알림") { notifyTab = tab; break; }
        }

        if (notifyTab?.Content is ScrollViewer sv && sv.Content is StackPanel sp)
        {
            // 내용물을 NotifyContent로 복제 이동
            var children = sp.Children.Cast<UIElement>().ToList();
            sp.Children.Clear();
            foreach (var child in children)
                NotifyContent.Children.Add(child);
        }

        // 알림 탭 숨기기
        if (notifyTab != null) notifyTab.Visibility = Visibility.Collapsed;
    }

    private static T? FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);
            if (child is T t) return t;
            var result = FindVisualChild<T>(child);
            if (result != null) return result;
        }
        return null;
    }

    // ─── 독 바 설정 ────────────────────────────────────────────────────────────

    private void BuildDockBarSettings()
    {
        var svc = CurrentApp?.SettingsService;
        if (svc == null) return;
        var launcher = svc.Settings.Launcher;

        // 토글 바인딩
        ChkDockAutoShow.IsChecked = launcher.DockBarAutoShow;
        ChkDockAutoShow.Checked += (_, _) =>
        {
            launcher.DockBarAutoShow = true; svc.Save();
            CurrentApp?.ToggleDockBar();
        };
        ChkDockAutoShow.Unchecked += (_, _) =>
        {
            launcher.DockBarAutoShow = false; svc.Save();
            // 끄기 시에는 설정만 저장 — 독 바를 토글하지 않음 (이미 표시 중이면 유지, 다음 재시작 시 안 뜸)
        };

        ChkDockRainbowGlow.IsChecked = launcher.DockBarRainbowGlow;
        ChkDockRainbowGlow.Checked += (_, _) => { launcher.DockBarRainbowGlow = true; svc.Save(); RefreshDock(); };
        ChkDockRainbowGlow.Unchecked += (_, _) => { launcher.DockBarRainbowGlow = false; svc.Save(); RefreshDock(); };

        SliderDockOpacity.Value = launcher.DockBarOpacity;
        SliderDockOpacity.ValueChanged += (_, e) => { launcher.DockBarOpacity = e.NewValue; svc.Save(); RefreshDock(); };

        // 표시 항목 토글 리스트
        if (DockItemsPanel == null) return;
        DockItemsPanel.Children.Clear();
        var toggleStyle = TryFindResource("ToggleSwitch") as System.Windows.Style;
        var enabled = launcher.DockBarItems;

        foreach (var (key, icon, tooltip) in DockBarWindow.AvailableItems)
        {
            var row = new System.Windows.Controls.Grid { Margin = new Thickness(0, 3, 0, 3) };
            row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });

            var label = new TextBlock
            {
                Text = $"{tooltip}",
                FontSize = 12.5,
                VerticalAlignment = VerticalAlignment.Center,
                Foreground = TryFindResource("PrimaryText") as System.Windows.Media.Brush ?? System.Windows.Media.Brushes.Black,
            };
            System.Windows.Controls.Grid.SetColumn(label, 0);
            row.Children.Add(label);

            var capturedKey = key;
            var cb = new CheckBox
            {
                IsChecked = enabled.Contains(key),
                HorizontalAlignment = HorizontalAlignment.Right,
                VerticalAlignment = VerticalAlignment.Center,
            };
            if (toggleStyle != null) cb.Style = toggleStyle;
            cb.Checked += (_, _) => { if (!enabled.Contains(capturedKey)) enabled.Add(capturedKey); svc.Save(); RefreshDock(); };
            cb.Unchecked += (_, _) => { enabled.RemoveAll(x => x == capturedKey); svc.Save(); RefreshDock(); };
            System.Windows.Controls.Grid.SetColumn(cb, 1);
            row.Children.Add(cb);

            DockItemsPanel.Children.Add(row);
        }
    }

    private static SolidColorBrush BrushFromHex(string hex)
    {
        try { return ThemeResourceHelper.HexBrush(hex); }
        catch (Exception) { return new SolidColorBrush(Colors.Gray); }
    }

    private static void RefreshDock()
    {
        CurrentApp?.RefreshDockBar();
    }

    private void BtnDockResetPosition_Click(object sender, RoutedEventArgs e)
    {
        var result = CustomMessageBox.Show(
            "독 바를 화면 하단 중앙으로 이동하시겠습니까?",
            "독 바 위치 초기화",
            MessageBoxButton.YesNo, MessageBoxImage.Question);
        if (result != MessageBoxResult.Yes) return;

        var svc = CurrentApp?.SettingsService;
        if (svc == null) return;
        svc.Settings.Launcher.DockBarLeft = -1;
        svc.Settings.Launcher.DockBarTop = -1;
        svc.Save();

        // 즉시 독 바 위치 이동
        CurrentApp?.RefreshDockBar();
    }

    // ─── 알림 카테고리 체크박스 ───────────────────────────────────────────────

    private void BuildQuoteCategoryCheckboxes()
    {
        if (QuoteCategoryPanel == null) return;
        QuoteCategoryPanel.Children.Clear();

        var enabled = _vm.GetReminderCategories();
        var toggleStyle = TryFindResource("ToggleSwitch") as Style;

        foreach (var (key, label, countFunc) in Services.QuoteService.Categories)
        {
            var count = countFunc();
            var displayLabel = key == "today_events"
                ? $"{label} ({count}개, 오늘 {Services.QuoteService.GetTodayMatchCount()}개)"
                : $"{label} ({count}개)";

            // 좌: 라벨, 우: 토글 스위치
            var row = new Grid { Margin = new Thickness(0, 3, 0, 3) };
            row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });

            var labelBlock = new TextBlock
            {
                Text = displayLabel,
                FontSize = 12.5,
                VerticalAlignment = VerticalAlignment.Center,
                Foreground = TryFindResource("PrimaryText") as System.Windows.Media.Brush
                             ?? System.Windows.Media.Brushes.White,
            };
            Grid.SetColumn(labelBlock, 0);
            row.Children.Add(labelBlock);

            var cb = new CheckBox
            {
                IsChecked = enabled.Contains(key, StringComparer.OrdinalIgnoreCase),
                Tag = key,
                HorizontalAlignment = HorizontalAlignment.Right,
                VerticalAlignment = VerticalAlignment.Center,
            };
            if (toggleStyle != null) cb.Style = toggleStyle;
            cb.Checked += (s, _) =>
            {
                if (s is CheckBox c && c.Tag is string k && !enabled.Contains(k))
                    enabled.Add(k);
            };
            cb.Unchecked += (s, _) =>
            {
                if (s is CheckBox c && c.Tag is string k)
                    enabled.RemoveAll(x => x.Equals(k, StringComparison.OrdinalIgnoreCase));
            };
            Grid.SetColumn(cb, 1);
            row.Children.Add(cb);

            QuoteCategoryPanel.Children.Add(row);
        }
    }

    // ─── 기능 설정 서브탭 전환 ──────────────────────────────────────────
    private void FuncSubTab_Checked(object sender, RoutedEventArgs e)
    {
        if (FuncPanel_AI == null) return; // 초기화 전 방어

        FuncPanel_AI.Visibility       = FuncSubTab_AI.IsChecked == true       ? Visibility.Visible : Visibility.Collapsed;
        FuncPanel_Launcher.Visibility = FuncSubTab_Launcher.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
        FuncPanel_Design.Visibility   = FuncSubTab_Design.IsChecked == true   ? Visibility.Visible : Visibility.Collapsed;
    }

    // ─── 접기/열기 섹션 토글 ───────────────────────────────────────────
    private void CollapsibleSection_Toggle(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (sender is Border border && border.Tag is System.Windows.Controls.Expander expander)
            expander.IsExpanded = !expander.IsExpanded;
    }

    private void ServiceSubTab_Checked(object sender, RoutedEventArgs e)
    {
        if (SvcPanelOllama == null) return; // 초기화 전 방어
        SvcPanelOllama.Visibility = SvcTabOllama.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
        SvcPanelVllm.Visibility   = SvcTabVllm.IsChecked   == true ? Visibility.Visible : Visibility.Collapsed;
        SvcPanelGemini.Visibility = SvcTabGemini.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
        SvcPanelClaude.Visibility = SvcTabClaude.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
    }

    private void ThemeCard_Click(object sender, RoutedEventArgs e)
    {
        if (sender is Button btn && btn.Tag is string key)
            _vm.SelectTheme(key);
    }

    private void ColorSwatch_Click(object sender, RoutedEventArgs e)
    {
        if (sender is Button btn && btn.Tag is ColorRowModel row)
            _vm.PickColor(row);
    }
}
