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

namespace AxCopilot.Views;

public partial class HelpDetailWindow
{
    // ─── 테마 색상 헬퍼 ───────────────────────────────────────────────────────
    private Brush ThemeAccent => TryFindResource("AccentColor") as Brush ?? ParseColor("#4B5EFC");
    private Brush ThemePrimary => TryFindResource("PrimaryText") as Brush ?? Brushes.White;
    private Brush ThemeSecondary => TryFindResource("SecondaryText") as Brush ?? ParseColor("#8899CC");

    // ─── 상단 3탭 메뉴 빌드 ──────────────────────────────────────────────────

    private void BuildTopMenu()
    {
        TopMenuBar.Children.Clear();
        foreach (var (key, label, icon) in TopMenus)
        {
            var k = key;
            var sp = new StackPanel { Orientation = Orientation.Horizontal };
            sp.Children.Add(new TextBlock
            {
                Text = icon,
                FontFamily = ThemeResourceHelper.SegoeMdl2,
                FontSize = 14,
                Foreground = ThemeAccent,
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(0, 0, 6, 0)
            });
            sp.Children.Add(new TextBlock
            {
                Text = label,
                FontSize = 12,
                VerticalAlignment = VerticalAlignment.Center
            });

            var btn = new Button
            {
                Content = sp,
                FontWeight = FontWeights.SemiBold,
                Padding = new Thickness(16, 8, 16, 8),
                Margin = new Thickness(4, 0, 4, 0),
                Cursor = Cursors.Hand,
                Background = Brushes.Transparent,
                Foreground = ThemeSecondary,
                BorderThickness = new Thickness(0, 0, 0, 2),
                BorderBrush = Brushes.Transparent,
                Tag = k,
            };
            btn.Click += (_, _) => SwitchTopMenu(k);
            TopMenuBar.Children.Add(btn);
        }
    }

    private void SwitchTopMenu(TopMenu menu)
    {
        _currentTopMenu = menu;

        // 상단 메뉴 하이라이트
        foreach (var child in TopMenuBar.Children)
        {
            if (child is Button btn)
            {
                var isActive = btn.Tag is TopMenu t && t == menu;
                btn.BorderBrush = isActive ? ThemeAccent : Brushes.Transparent;
                btn.Foreground = isActive ? ThemePrimary : ThemeSecondary;

                // 내부 TextBlock의 Foreground도 업데이트
                if (btn.Content is StackPanel sp)
                {
                    foreach (var spChild in sp.Children)
                    {
                        if (spChild is TextBlock tb && tb.FontFamily.Source != "Segoe MDL2 Assets")
                            tb.Foreground = btn.Foreground;
                    }
                }
            }
        }

        // 하위 카테고리 탭 빌드
        switch (menu)
        {
            case TopMenu.Overview:
                BuildCategoryBarFor(_overviewItems);
                break;
            case TopMenu.Shortcuts:
                BuildCategoryBarFor(_shortcutItems);
                break;
            case TopMenu.Prefixes:
                BuildCategoryBarFor(_prefixItems);
                break;
        }
    }

    // ─── 하위 카테고리 탭 빌드 ────────────────────────────────────────────────

    private void BuildCategoryBarFor(List<HelpItemModel> sourceItems)
    {
        var seen = new HashSet<string>();
        _categories = new List<string> { CatAll };

        // 예약어 탭에서만 인기 카테고리 표시
        if (_currentTopMenu == TopMenu.Prefixes)
            _categories.Add(CatPopular);

        foreach (var item in sourceItems)
        {
            if (seen.Add(item.Category))
                _categories.Add(item.Category);
        }

        BuildCategoryBar();
        NavigateToPage(0);
    }

    private void BuildCategoryBar()
    {
        CategoryBar.Children.Clear();
        for (int i = 0; i < _categories.Count; i++)
        {
            var cat = _categories[i];
            var idx = i;

            var btn = new Button
            {
                Content    = cat,
                FontSize   = 10.5,
                FontWeight = FontWeights.SemiBold,
                Padding    = new Thickness(9, 4, 9, 4),
                Margin     = new Thickness(0, 0, 3, 0),
                Cursor     = Cursors.Hand,
                Background = Brushes.Transparent,
                Foreground = ThemeSecondary,
                BorderThickness = new Thickness(0),
                Tag = idx,
            };

            btn.Click += (_, _) => NavigateToPage(idx);
            CategoryBar.Children.Add(btn);
        }
    }

    // ─── 페이지 네비게이션 ──────────────────────────────────────────────────

    private List<HelpItemModel> GetCurrentSourceItems() => _currentTopMenu switch
    {
        TopMenu.Overview  => _overviewItems,
        TopMenu.Shortcuts => _shortcutItems,
        TopMenu.Prefixes  => _prefixItems,
        _ => _overviewItems,
    };

    private void NavigateToPage(int pageIndex)
    {
        if (_categories.Count == 0) return;
        _currentPage = Math.Clamp(pageIndex, 0, _categories.Count - 1);

        var source = GetCurrentSourceItems();
        var cat = _categories[_currentPage];
        List<HelpItemModel> filtered;

        if (cat == CatAll)
            filtered = source;
        else if (cat == CatPopular)
        {
            var popularCmds = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
                { "파일/폴더", "?", "#", "!", "clip", "pipe", "diff", "win" };
            filtered = source.Where(i =>
                popularCmds.Contains(i.Command) ||
                i.Command.StartsWith("?") ||
                i.Title.Contains("검색") ||
                i.Title.Contains("클립보드") ||
                (i.Title.Contains("파일") && i.Category != "키보드")
            ).ToList();
        }
        else
            filtered = source.Where(i => i.Category == cat).ToList();

        ItemsHost.ItemsSource = filtered;

        // 탭 하이라이트
        for (int i = 0; i < CategoryBar.Children.Count; i++)
        {
            if (CategoryBar.Children[i] is Button btn)
            {
                if (i == _currentPage)
                {
                    btn.Background = ThemeAccent;
                    btn.Foreground = Brushes.White;
                }
                else
                {
                    btn.Background = Brushes.Transparent;
                    btn.Foreground = ThemeSecondary;
                }
            }
        }

        PageIndicator.Text = $"{cat}  ({filtered.Count}개)";
        PrevBtn.Visibility = _currentPage > 0 ? Visibility.Visible : Visibility.Hidden;
        NextBtn.Visibility = _currentPage < _categories.Count - 1 ? Visibility.Visible : Visibility.Hidden;
    }

    // ─── 이벤트 ────────────────────────────────────────────────────────────

    private void OnKeyDown(object sender, KeyEventArgs e)
    {
        switch (e.Key)
        {
            case Key.Escape:
                Close();
                break;
            case Key.Left:
                if (_currentPage > 0) NavigateToPage(_currentPage - 1);
                e.Handled = true;
                break;
            case Key.Right:
                if (_currentPage < _categories.Count - 1) NavigateToPage(_currentPage + 1);
                e.Handled = true;
                break;
            // 1, 2, 3 숫자키로 상단 메뉴 전환
            case Key.D1: SwitchTopMenu(TopMenu.Overview);  e.Handled = true; break;
            case Key.D2: SwitchTopMenu(TopMenu.Shortcuts); e.Handled = true; break;
            case Key.D3: SwitchTopMenu(TopMenu.Prefixes);  e.Handled = true; break;
        }
    }

    private void Prev_Click(object sender, RoutedEventArgs e) => NavigateToPage(_currentPage - 1);
    private void Next_Click(object sender, RoutedEventArgs e) => NavigateToPage(_currentPage + 1);
    private void Close_Click(object sender, RoutedEventArgs e) => Close();

    private void SearchBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
    {
        var query = SearchBox.Text.Trim();
        if (string.IsNullOrEmpty(query))
        {
            NavigateToPage(_currentPage);
            return;
        }

        var source = GetCurrentSourceItems();
        var filtered = source.Where(i =>
            i.Title.Contains(query, StringComparison.OrdinalIgnoreCase) ||
            i.Command.Contains(query, StringComparison.OrdinalIgnoreCase) ||
            i.Description.Contains(query, StringComparison.OrdinalIgnoreCase) ||
            i.Category.Contains(query, StringComparison.OrdinalIgnoreCase)
        ).ToList();

        ItemsHost.ItemsSource = filtered;
        PageIndicator.Text = $"검색: \"{query}\"  ({filtered.Count}개)";
    }

    private void Window_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (e.ChangedButton == MouseButton.Left && e.LeftButton == MouseButtonState.Pressed)
            try { DragMove(); } catch (Exception) { }
    }

    private void Window_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Escape) Close();
    }
}
