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

namespace AxCopilot.Views.Controls;

/// <summary>
/// Phase 17-UI-E: 멀티기능 입력 영역.
/// @ 멘션, / 스킬, 첨부, Ctrl+Enter 전송, 모델/권한/Plan 칩 표시.
/// IsToolbarOnly=True 시 상단 툴바 행(@/스킬/첨부)만 표시하고
/// TextBox 행과 칩/전송 행은 숨깁니다 (ChatWindow 기존 InputBox 위에 배치용).
/// </summary>
public partial class AgentInputArea : UserControl
{
    private bool _isStreaming;

    // ── IsToolbarOnly 의존성 프로퍼티 ─────────────────────────────────────

    public static readonly DependencyProperty IsToolbarOnlyProperty =
        DependencyProperty.Register(
            nameof(IsToolbarOnly),
            typeof(bool),
            typeof(AgentInputArea),
            new PropertyMetadata(false, OnIsToolbarOnlyChanged));

    /// <summary>True이면 @/스킬/첨부 툴바 행만 표시합니다.</summary>
    public bool IsToolbarOnly
    {
        get => (bool)GetValue(IsToolbarOnlyProperty);
        set => SetValue(IsToolbarOnlyProperty, value);
    }

    private static void OnIsToolbarOnlyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is AgentInputArea ctrl)
            ctrl.ApplyToolbarOnlyMode((bool)e.NewValue);
    }

    private void ApplyToolbarOnlyMode(bool toolbarOnly)
    {
        var vis = toolbarOnly ? Visibility.Collapsed : Visibility.Visible;
        if (InputTextBoxRow != null)  InputTextBoxRow.Visibility = vis;
        if (ChipsSendRow != null)     ChipsSendRow.Visibility    = vis;
        // 툴바 전용 모드에서는 외부 Border 배경/테두리를 투명하게 처리
        if (OuterBorder != null)
        {
            OuterBorder.BorderThickness = toolbarOnly ? new Thickness(0) : new Thickness(0, 1, 0, 0);
            OuterBorder.Padding         = toolbarOnly ? new Thickness(8, 0, 8, 0) : new Thickness(16, 8, 16, 8);
            OuterBorder.Background      = toolbarOnly
                ? System.Windows.Media.Brushes.Transparent
                : TryFindResource("LauncherBackground") as System.Windows.Media.Brush
                    ?? System.Windows.Media.Brushes.Transparent;
        }
    }

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

    /// <summary>메시지 전송 이벤트. 인자: 입력 텍스트.</summary>
    public event EventHandler<string>? MessageSent;

    /// <summary>중단 요청 이벤트.</summary>
    public event EventHandler? StopRequested;

    /// <summary>@ 멘션 클릭 이벤트.</summary>
    public event EventHandler? MentionRequested;

    /// <summary>/ 스킬 클릭 이벤트.</summary>
    public event EventHandler? SkillRequested;

    /// <summary>첨부 클릭 이벤트.</summary>
    public event EventHandler? AttachRequested;

    // ── 공개 API ──────────────────────────────────────────────────────────

    /// <summary>입력 텍스트.</summary>
    public string Text
    {
        get => InputBox.Text;
        set => InputBox.Text = value;
    }

    /// <summary>스트리밍 상태 (전송 → 중단 버튼 전환).</summary>
    public bool IsStreaming
    {
        get => _isStreaming;
        set
        {
            _isStreaming = value;
            UpdateSendButton(value);
        }
    }

    public AgentInputArea()
    {
        InitializeComponent();
        // Loaded 후 IsToolbarOnly 초기 적용 (XAML 설정값 반영)
        Loaded += (_, _) =>
        {
            if (IsToolbarOnly) ApplyToolbarOnlyMode(true);
        };
    }

    /// <summary>하단 칩 텍스트를 업데이트합니다.</summary>
    public void UpdateChips(string model, string permission, string planMode)
    {
        TxtModelChip.Text = model.Length > 15 ? model[..15] + "…" : model;
        TxtPermissionChip.Text = permission;
        TxtPlanChip.Text = planMode switch
        {
            "auto" => "Plan: Auto",
            "always" => "Plan: Always",
            _ => "Plan: Off",
        };
    }

    /// <summary>첨부 파일 칩을 추가합니다.</summary>
    public void AddAttachmentChip(string fileName)
    {
        var chip = new Border
        {
            CornerRadius = new CornerRadius(8),
            Padding = new Thickness(6, 2, 6, 2),
            Margin = new Thickness(0, 0, 4, 0),
            Background = TryFindResource("ItemBackground") as System.Windows.Media.Brush,
        };
        var sp = new StackPanel { Orientation = Orientation.Horizontal };
        sp.Children.Add(new TextBlock
        {
            Text = fileName,
            FontSize = 10,
            Foreground = TryFindResource("SecondaryText") as System.Windows.Media.Brush,
            MaxWidth = 100,
            TextTrimming = TextTrimming.CharacterEllipsis,
        });
        // 제거 버튼
        var remove = new TextBlock
        {
            Text = "\xE711",
            FontFamily = new System.Windows.Media.FontFamily("Segoe MDL2 Assets"),
            FontSize = 8,
            Foreground = TryFindResource("SecondaryText") as System.Windows.Media.Brush,
            Margin = new Thickness(4, 0, 0, 0),
            Cursor = Cursors.Hand,
            VerticalAlignment = VerticalAlignment.Center,
        };
        remove.MouseLeftButtonUp += (_, _) => AttachmentChips.Children.Remove(chip);
        sp.Children.Add(remove);
        chip.Child = sp;
        AttachmentChips.Children.Add(chip);
    }

    /// <summary>첨부 파일 목록을 초기화합니다.</summary>
    public void ClearAttachments() => AttachmentChips.Children.Clear();

    /// <summary>입력 포커스를 설정합니다.</summary>
    public void FocusInput() => InputBox.Focus();

    // ── 이벤트 핸들러 ────────────────────────────────────────────────────

    private void InputBox_KeyDown(object sender, KeyEventArgs e)
    {
        // Ctrl+Enter → 전송
        if (e.Key == Key.Enter && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
        {
            e.Handled = true;
            TrySend();
        }
    }

    private void InputBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        // 높이 자동 조절은 TextBox의 MinHeight/MaxHeight로 처리됨
    }

    private void BtnSend_Click(object sender, MouseButtonEventArgs e)
    {
        if (_isStreaming)
            StopRequested?.Invoke(this, EventArgs.Empty);
        else
            TrySend();
    }

    private void BtnMention_Click(object sender, MouseButtonEventArgs e)
        => MentionRequested?.Invoke(this, EventArgs.Empty);

    private void BtnSkill_Click(object sender, MouseButtonEventArgs e)
        => SkillRequested?.Invoke(this, EventArgs.Empty);

    private void BtnAttach_Click(object sender, MouseButtonEventArgs e)
        => AttachRequested?.Invoke(this, EventArgs.Empty);

    // ── 내부 헬퍼 ────────────────────────────────────────────────────────

    private void TrySend()
    {
        var text = InputBox.Text.Trim();
        if (string.IsNullOrEmpty(text)) return;

        MessageSent?.Invoke(this, text);
        InputBox.Clear();
        ClearAttachments();
    }

    private void UpdateSendButton(bool streaming)
    {
        if (streaming)
        {
            IconSend.Text = "\xE71A"; // Stop icon
            TxtSendLabel.Text = " 중단";
            BtnSend.Background = TryFindResource("ItemBackground") as System.Windows.Media.Brush;
        }
        else
        {
            IconSend.Text = "\xE724"; // Send icon
            TxtSendLabel.Text = " 전송";
            BtnSend.Background = TryFindResource("AccentColor") as System.Windows.Media.Brush;
        }
    }
}
