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

namespace AxCopilot.Views;

public partial class ChatWindow
{
    // ─── 버튼 이벤트 ──────────────────────────────────────────────────────

    private void ChatWindow_KeyDown(object sender, KeyEventArgs e)
    {
        var mod = Keyboard.Modifiers;

        // Ctrl 단축키
        if (mod == ModifierKeys.Control)
        {
            switch (e.Key)
            {
                case Key.N: BtnNewChat_Click(this, new RoutedEventArgs()); e.Handled = true; break;
                case Key.W: Close(); e.Handled = true; break;
                case Key.E: ExportConversation(); e.Handled = true; break;
                case Key.L: InputBox.Text = ""; InputBox.Focus(); e.Handled = true; break;
                case Key.B: BtnToggleSidebar_Click(this, new RoutedEventArgs()); e.Handled = true; break;
                case Key.M: BtnModelSelector_Click(this, new RoutedEventArgs()); e.Handled = true; break;
                case Key.OemComma: BtnSettings_Click(this, new RoutedEventArgs()); e.Handled = true; break;
                case Key.F: ToggleMessageSearch(); e.Handled = true; break;
                case Key.D1: TabChat.IsChecked = true; e.Handled = true; break;
                case Key.D2: TabCowork.IsChecked = true; e.Handled = true; break;
                case Key.D3: if (TabCode.IsEnabled) TabCode.IsChecked = true; e.Handled = true; break;
            }
        }

        // Ctrl+Shift 단축키
        if (mod == (ModifierKeys.Control | ModifierKeys.Shift))
        {
            switch (e.Key)
            {
                case Key.C:
                    // 마지막 AI 응답 복사
                    ChatConversation? conv;
                    lock (_convLock) conv = _currentConversation;
                    if (conv != null)
                    {
                        var lastAi = conv.Messages.LastOrDefault(m => m.Role == "assistant");
                        if (lastAi != null)
                            try { Clipboard.SetText(lastAi.Content); } catch (Exception) { /* 클립보드 접근 실패 */ }
                    }
                    e.Handled = true;
                    break;
                case Key.R:
                    // 마지막 응답 재생성
                    _ = RegenerateLastAsync();
                    e.Handled = true;
                    break;
                case Key.D:
                    // 모든 대화 삭제
                    BtnDeleteAll_Click(this, new RoutedEventArgs());
                    e.Handled = true;
                    break;
                case Key.P:
                    // 커맨드 팔레트
                    OpenCommandPalette();
                    e.Handled = true;
                    break;
            }
        }

        // Escape: 검색 바 닫기 또는 스트리밍 중지
        if (e.Key == Key.Escape)
        {
            if (MessageSearchBar.Visibility == Visibility.Visible) { CloseMessageSearch(); e.Handled = true; }
            else if (_isStreaming) { StopGeneration(); e.Handled = true; }
        }

        // 슬래시 명령 팝업 키 처리
        if (SlashPopup.IsOpen)
        {
            if (e.Key == Key.Escape)
            {
                SlashPopup.IsOpen = false;
                _slashSelectedIndex = -1;
                e.Handled = true;
            }
            else if (e.Key == Key.Up)
            {
                SlashPopup_ScrollByDelta(120); // 위로 1칸
                e.Handled = true;
            }
            else if (e.Key == Key.Down)
            {
                SlashPopup_ScrollByDelta(-120); // 아래로 1칸
                e.Handled = true;
            }
            else if (e.Key == Key.Enter && _slashSelectedIndex >= 0)
            {
                e.Handled = true;
                ExecuteSlashSelectedItem();
            }
        }
    }

    private void BtnStop_Click(object sender, RoutedEventArgs e) => StopGeneration();

    private void BtnPause_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (_agentLoop.IsPaused)
        {
            _agentLoop.Resume();
            PauseIcon.Text = "\uE769"; // 일시정지 아이콘
            BtnPause.ToolTip = "일시정지";
        }
        else
        {
            _ = _agentLoop.PauseAsync();
            PauseIcon.Text = "\uE768"; // 재생 아이콘
            BtnPause.ToolTip = "재개";
        }
    }
    private void BtnExport_Click(object sender, RoutedEventArgs e) => ExportConversation();

    // ─── 메시지 내 검색 (Ctrl+F) ─────────────────────────────────────────

    private List<int> _searchMatchIndices = new();
    private int _searchCurrentIndex = -1;

    private void ToggleMessageSearch()
    {
        if (MessageSearchBar.Visibility == Visibility.Visible)
            CloseMessageSearch();
        else
        {
            MessageSearchBar.Visibility = Visibility.Visible;
            SearchTextBox.Focus();
            SearchTextBox.SelectAll();
        }
    }

    private void CloseMessageSearch()
    {
        MessageSearchBar.Visibility = Visibility.Collapsed;
        SearchTextBox.Text = "";
        SearchResultCount.Text = "";
        _searchMatchIndices.Clear();
        _searchCurrentIndex = -1;
        // 하이라이트 제거
        ClearSearchHighlights();
    }

    private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        var query = SearchTextBox.Text.Trim();
        if (string.IsNullOrEmpty(query))
        {
            SearchResultCount.Text = "";
            _searchMatchIndices.Clear();
            _searchCurrentIndex = -1;
            ClearSearchHighlights();
            return;
        }

        // 현재 대화의 메시지에서 검색
        ChatConversation? conv;
        lock (_convLock) conv = _currentConversation;
        if (conv == null) return;

        _searchMatchIndices.Clear();
        for (int i = 0; i < conv.Messages.Count; i++)
        {
            if (conv.Messages[i].Content.Contains(query, StringComparison.OrdinalIgnoreCase))
                _searchMatchIndices.Add(i);
        }

        if (_searchMatchIndices.Count > 0)
        {
            _searchCurrentIndex = 0;
            SearchResultCount.Text = $"1/{_searchMatchIndices.Count}";
            HighlightSearchResult();
        }
        else
        {
            _searchCurrentIndex = -1;
            SearchResultCount.Text = "결과 없음";
        }
    }

    private void SearchPrev_Click(object sender, RoutedEventArgs e)
    {
        if (_searchMatchIndices.Count == 0) return;
        _searchCurrentIndex = (_searchCurrentIndex - 1 + _searchMatchIndices.Count) % _searchMatchIndices.Count;
        SearchResultCount.Text = $"{_searchCurrentIndex + 1}/{_searchMatchIndices.Count}";
        HighlightSearchResult();
    }

    private void SearchNext_Click(object sender, RoutedEventArgs e)
    {
        if (_searchMatchIndices.Count == 0) return;
        _searchCurrentIndex = (_searchCurrentIndex + 1) % _searchMatchIndices.Count;
        SearchResultCount.Text = $"{_searchCurrentIndex + 1}/{_searchMatchIndices.Count}";
        HighlightSearchResult();
    }

    private void SearchClose_Click(object sender, RoutedEventArgs e) => CloseMessageSearch();

    private void HighlightSearchResult()
    {
        if (_searchCurrentIndex < 0 || _searchCurrentIndex >= _searchMatchIndices.Count) return;
        var msgIndex = _searchMatchIndices[_searchCurrentIndex];

        if (msgIndex < MessagePanel.Children.Count)
        {
            var element = MessagePanel.Children[msgIndex] as FrameworkElement;
            element?.BringIntoView();
        }
        else if (MessagePanel.Children.Count > 0)
        {
            // 범위 밖이면 마지막 자식으로 이동
            (MessagePanel.Children[^1] as FrameworkElement)?.BringIntoView();
        }
    }

    private void ClearSearchHighlights()
    {
        // 현재는 BringIntoView 기반이므로 별도 하이라이트 제거 불필요
    }

    // ─── 에러 복구 재시도 버튼 ──────────────────────────────────────────────

    private void AddRetryButton()
    {
        Dispatcher.Invoke(() =>
        {
            var retryBorder = new Border
            {
                Background = new SolidColorBrush(Color.FromArgb(0x18, 0xEF, 0x44, 0x44)),
                CornerRadius = new CornerRadius(8),
                Padding = new Thickness(12, 8, 12, 8),
                Margin = new Thickness(40, 4, 80, 4),
                HorizontalAlignment = HorizontalAlignment.Left,
                Cursor = System.Windows.Input.Cursors.Hand,
            };
            var retrySp = new StackPanel { Orientation = Orientation.Horizontal };
            retrySp.Children.Add(new TextBlock
            {
                Text = "\uE72C", FontFamily = ThemeResourceHelper.SegoeMdl2,
                FontSize = 12, Foreground = new SolidColorBrush(Color.FromRgb(0xEF, 0x44, 0x44)),
                VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 6, 0),
            });
            retrySp.Children.Add(new TextBlock
            {
                Text = "재시도", FontSize = 12, FontWeight = FontWeights.SemiBold,
                Foreground = new SolidColorBrush(Color.FromRgb(0xEF, 0x44, 0x44)),
                VerticalAlignment = VerticalAlignment.Center,
            });
            retryBorder.Child = retrySp;
            retryBorder.MouseEnter += (s, _) => { if (s is Border b) b.Background = new SolidColorBrush(Color.FromArgb(0x30, 0xEF, 0x44, 0x44)); };
            retryBorder.MouseLeave += (s, _) => { if (s is Border b) b.Background = new SolidColorBrush(Color.FromArgb(0x18, 0xEF, 0x44, 0x44)); };
            retryBorder.MouseLeftButtonUp += (_, _) =>
            {
                lock (_convLock)
                {
                    if (_currentConversation != null)
                    {
                        var lastIdx = _currentConversation.Messages.Count - 1;
                        if (lastIdx >= 0 && _currentConversation.Messages[lastIdx].Role == "assistant")
                            _currentConversation.Messages.RemoveAt(lastIdx);
                    }
                }
                _ = RegenerateLastAsync();
            };
            MessagePanel.Children.Add(retryBorder);
            ForceScrollToEnd();
        });
    }
}
