using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace AxCopilot.Views.Controls;

/// <summary>
/// Phase 17-UI-D: 좌측 사이드바 UserControl.
/// 기존 SidebarPanel Grid를 대체. ChatWindow 프록시 패턴으로 기존 코드와 호환.
/// 탭 세그먼트(Chat/Cowork/Code) + 카테고리 필터 + 대화 목록 + 사용자 계정.
/// </summary>
public partial class AgentSidebarView : UserControl
{
    private string _activeTab = "Chat";

    // ── 프록시 프로퍼티 (ChatWindow 기존 코드가 직접 참조) ─────────────────
    internal StackPanel SidebarConversationPanel => ConversationPanel;
    internal TextBox    SidebarSearchBox         => SearchBox;
    internal TextBlock  SidebarCategoryIcon      => CategoryIcon;
    internal TextBlock  SidebarCategoryLabel     => CategoryLabel;
    internal Border     SidebarCategoryDropTarget => BtnCategoryDrop;
    internal TextBlock  SidebarUserInitial        => UserInitialSidebar;
    internal TextBlock  SidebarUserName           => UserNameText;
    internal TextBlock  SidebarUserPc             => UserPcText;

    // ── 이벤트 (ChatWindow가 구독) ─────────────────────────────────────────
    /// <summary>탭 전환 이벤트. 인자: 탭 이름 ("Chat", "Cowork", "Code").</summary>
    public event EventHandler<string>? SidebarTabChanged;

    /// <summary>새 대화 요청 이벤트.</summary>
    public event EventHandler? NewChatRequested;

    /// <summary>전체 삭제 요청 이벤트.</summary>
    public event EventHandler? DeleteAllRequested;

    /// <summary>카테고리 드롭다운 클릭 이벤트.</summary>
    public event EventHandler? CategoryDropClicked;

    /// <summary>검색어 변경 이벤트.</summary>
    public event TextChangedEventHandler? SearchTextChanged;

    public AgentSidebarView()
    {
        InitializeComponent();
        UpdateTabHighlight("Chat");
    }

    // ── 외부 제어 ───────────────────────────────────────────────────────────

    /// <summary>탭을 외부에서 변경합니다 (이벤트 발행 없음).</summary>
    public void SetActiveTab(string tab)
    {
        _activeTab = tab;
        UpdateTabHighlight(tab);
    }

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

    private void BtnNewChat_Click(object sender, RoutedEventArgs e)
        => NewChatRequested?.Invoke(this, EventArgs.Empty);

    private void SidebarTabChat_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (_activeTab == "Chat") return;
        _activeTab = "Chat";
        UpdateTabHighlight("Chat");
        SidebarTabChanged?.Invoke(this, "Chat");
    }

    private void SidebarTabCowork_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (_activeTab == "Cowork") return;
        _activeTab = "Cowork";
        UpdateTabHighlight("Cowork");
        SidebarTabChanged?.Invoke(this, "Cowork");
    }

    private void SidebarTabCode_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (_activeTab == "Code") return;
        _activeTab = "Code";
        UpdateTabHighlight("Code");
        SidebarTabChanged?.Invoke(this, "Code");
    }

    private void SearchBox_TextChanged(object sender, TextChangedEventArgs e)
        => SearchTextChanged?.Invoke(sender, e);

    private void BtnCategoryDrop_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
        => CategoryDropClicked?.Invoke(this, EventArgs.Empty);

    private void BtnDeleteAll_Click(object sender, RoutedEventArgs e)
        => DeleteAllRequested?.Invoke(this, EventArgs.Empty);

    // ── UI 헬퍼 ─────────────────────────────────────────────────────────────

    private void UpdateTabHighlight(string tab)
    {
        var accentBrush = TryFindResource("AccentColor") as Brush
                          ?? new SolidColorBrush(Color.FromRgb(0x4B, 0x5E, 0xFC));
        var transparentBrush = Brushes.Transparent;

        SidebarTabChat.Background   = tab == "Chat"   ? accentBrush : transparentBrush;
        SidebarTabCowork.Background = tab == "Cowork" ? accentBrush : transparentBrush;
        SidebarTabCode.Background   = tab == "Code"   ? accentBrush : transparentBrush;

        SetTabTextColor(SidebarTabChat,   tab == "Chat");
        SetTabTextColor(SidebarTabCowork, tab == "Cowork");
        SetTabTextColor(SidebarTabCode,   tab == "Code");
    }

    private void SetTabTextColor(Border tabBorder, bool isActive)
    {
        if (tabBorder.Child is TextBlock txt)
        {
            txt.Foreground = isActive
                ? Brushes.White
                : (TryFindResource("PrimaryText") as Brush ?? Brushes.White);
        }
    }
}
