using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Media;
using AxCopilot.Themes;
using AxCopilot.Views;

namespace AxCopilot.ViewModels;

/// <summary>
/// 설정 카드에 표시할 테마 미리보기 데이터
/// </summary>
public class ThemeCardModel : INotifyPropertyChanged
{
    private bool _isSelected;

    public string Key  { get; init; } = "";   // settings.json 값 (dark, light, ...)
    public string Name { get; init; } = "";   // 표시 이름

    // 미리보기용 색상
    public string PreviewBackground { get; init; } = "#1A1B2E";
    public string PreviewText       { get; init; } = "#F0F0FF";
    public string PreviewSubText    { get; init; } = "#7A7D9C";
    public string PreviewAccent     { get; init; } = "#4B5EFC";
    public string PreviewItem       { get; init; } = "#252637";
    public string PreviewBorder     { get; init; } = "#2E2F4A";

    public bool IsSelected
    {
        get => _isSelected;
        set { _isSelected = value; OnPropertyChanged(); }
    }

    public event PropertyChangedEventHandler? PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string? n = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(n));
}

/// <summary>
/// 커스텀 테마 단일 색상 항목 (색상 편집 탭 1행 1색)
/// </summary>
public class ColorRowModel : INotifyPropertyChanged
{
    private string _hex;

    public string Label    { get; init; } = "";
    public string Property { get; init; } = ""; // CustomThemeColors의 속성명

    public string Hex
    {
        get => _hex;
        set { _hex = value; OnPropertyChanged(); OnPropertyChanged(nameof(Preview)); }
    }

    public SolidColorBrush Preview
    {
        get
        {
            try { return ThemeResourceHelper.HexBrush(Hex); }
            catch (Exception) { return new SolidColorBrush(Colors.Transparent); }
        }
    }

    public ColorRowModel(string label, string property, string hex)
    {
        Label = label;
        Property = property;
        _hex = hex;
    }

    public event PropertyChangedEventHandler? PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string? n = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(n));
}

/// <summary>
/// 빠른 실행 단축키 항목 (키워드 → 앱/URL/폴더)
/// </summary>
public class AppShortcutModel : INotifyPropertyChanged
{
    private string _key         = "";
    private string _description = "";
    private string _target      = "";
    private string _type        = "app";

    public string Key         { get => _key;         set { _key = value;         OnPropertyChanged(); } }
    public string Description { get => _description; set { _description = value; OnPropertyChanged(); } }
    public string Target      { get => _target;      set { _target = value;      OnPropertyChanged(); } }
    public string Type        { get => _type;        set { _type = value;        OnPropertyChanged(); OnPropertyChanged(nameof(TypeSymbol)); OnPropertyChanged(nameof(TypeLabel)); } }

    public string TypeSymbol => Type switch
    {
        "url"    => Symbols.Globe,
        "folder" => Symbols.Folder,
        _        => Symbols.App
    };

    public string TypeLabel => Type switch
    {
        "url"    => "URL",
        "folder" => "폴더",
        _        => "앱"
    };

    public event PropertyChangedEventHandler? PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string? n = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(n));
}

/// <summary>
/// 배치 명령 항목 (> 프리픽스)
/// </summary>
public class BatchCommandModel : INotifyPropertyChanged
{
    private string _key     = "";
    private string _command = "";
    private bool   _showWindow;

    public string Key        { get => _key;        set { _key = value;        OnPropertyChanged(); } }
    public string Command    { get => _command;    set { _command = value;    OnPropertyChanged(); } }
    public bool   ShowWindow { get => _showWindow; set { _showWindow = value; OnPropertyChanged(); } }

    public event PropertyChangedEventHandler? PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string? n = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(n));
}

// ─── 프롬프트 템플릿 행 모델 ─────────────────────────────────────────────────────

public class PromptTemplateRow : INotifyPropertyChanged
{
    private string _name = "";
    private string _content = "";
    private string _icon = "\uE8BD";

    public string Name    { get => _name;    set { _name = value;    OnPropertyChanged(); } }
    public string Content { get => _content; set { _content = value; OnPropertyChanged(); OnPropertyChanged(nameof(Preview)); } }
    public string Icon    { get => _icon;    set { _icon = value;    OnPropertyChanged(); } }

    public string Preview => Content.Length > 60
        ? Content[..57].Replace("\n", " ") + "…"
        : Content.Replace("\n", " ");

    public event PropertyChangedEventHandler? PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string? n = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(n));
}

// ─── 등록 모델 행 모델 ──────────────────────────────────────────────────────────

public class RegisteredModelRow : INotifyPropertyChanged
{
    private string _alias = "";
    private string _encryptedModelName = "";
    private string _service = "ollama";
    private string _endpoint = "";
    private string _apiKey = "";

    /// <summary>UI 표시용 별칭</summary>
    public string Alias
    {
        get => _alias;
        set { _alias = value; OnPropertyChanged(); }
    }

    /// <summary>암호화된 실제 모델명 (PortableEncrypt)</summary>
    public string EncryptedModelName
    {
        get => _encryptedModelName;
        set { _encryptedModelName = value; OnPropertyChanged(); OnPropertyChanged(nameof(MaskedModelName)); }
    }

    /// <summary>서비스 타입 (ollama / vllm)</summary>
    public string Service
    {
        get => _service;
        set { _service = value; OnPropertyChanged(); OnPropertyChanged(nameof(ServiceLabel)); }
    }

    /// <summary>이 모델 전용 서버 엔드포인트. 비어있으면 기본 엔드포인트 사용.</summary>
    public string Endpoint
    {
        get => _endpoint;
        set { _endpoint = value; OnPropertyChanged(); OnPropertyChanged(nameof(EndpointDisplay)); }
    }

    /// <summary>이 모델 전용 API 키. 비어있으면 기본 API 키 사용.</summary>
    public string ApiKey
    {
        get => _apiKey;
        set { _apiKey = value; OnPropertyChanged(); }
    }

    // ── CP4D 인증 필드 ──────────────────────────────────────────────────

    private string _authType = "bearer";
    private string _cp4dUrl = "";
    private string _cp4dUsername = "";
    private string _cp4dPassword = "";

    /// <summary>인증 방식. bearer | cp4d</summary>
    public string AuthType
    {
        get => _authType;
        set { _authType = value; OnPropertyChanged(); OnPropertyChanged(nameof(AuthLabel)); }
    }

    /// <summary>CP4D 서버 URL</summary>
    public string Cp4dUrl
    {
        get => _cp4dUrl;
        set { _cp4dUrl = value; OnPropertyChanged(); }
    }

    /// <summary>CP4D 사용자 이름</summary>
    public string Cp4dUsername
    {
        get => _cp4dUsername;
        set { _cp4dUsername = value; OnPropertyChanged(); }
    }

    /// <summary>CP4D 비밀번호 (암호화 저장)</summary>
    public string Cp4dPassword
    {
        get => _cp4dPassword;
        set { _cp4dPassword = value; OnPropertyChanged(); }
    }

    /// <summary>인증 방식 라벨</summary>
    public string AuthLabel => _authType == "cp4d" ? "CP4D" : "Bearer";

    /// <summary>UI에 표시할 엔드포인트 요약</summary>
    public string EndpointDisplay => string.IsNullOrEmpty(_endpoint) ? "(기본 서버)" : _endpoint;

    /// <summary>UI에 표시할 마스킹된 모델명</summary>
    public string MaskedModelName => string.IsNullOrEmpty(_encryptedModelName) ? "(미등록)" : "••••••••";

    /// <summary>서비스 라벨</summary>
    public string ServiceLabel => _service == "vllm" ? "vLLM" : "Ollama";

    public event PropertyChangedEventHandler? PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string? n = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(n));
}

// ─── 전용 핫키 행 모델 ────────────────────────────────────────────────────────────

public class HotkeyRowModel : INotifyPropertyChanged
{
    private string _hotkey = "";
    private string _target = "";
    private string _label  = "";
    private string _type   = "app";

    public string Hotkey { get => _hotkey; set { _hotkey = value; OnPropertyChanged(); } }
    public string Target { get => _target; set { _target = value; OnPropertyChanged(); } }
    public string Label  { get => _label;  set { _label  = value; OnPropertyChanged(); } }
    public string Type   { get => _type;   set { _type   = value; OnPropertyChanged(); OnPropertyChanged(nameof(TypeSymbol)); } }

    public string TypeSymbol => Type switch
    {
        "url"     => Symbols.Globe,
        "folder"  => Symbols.Folder,
        "command" => "\uE756",   // Terminal
        _         => Symbols.App
    };

    public event PropertyChangedEventHandler? PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string? n = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(n));
}

// ─── 스니펫 행 모델 ────────────────────────────────────────────────────────────

public class SnippetRowModel : INotifyPropertyChanged
{
    private string _key     = "";
    private string _name    = "";
    private string _content = "";

    public string Key     { get => _key;     set { _key = value;     OnPropertyChanged(); } }
    public string Name    { get => _name;    set { _name = value;    OnPropertyChanged(); } }
    public string Content { get => _content; set { _content = value; OnPropertyChanged(); } }

    public string Preview => Content.Length > 50
        ? Content[..47].Replace("\n", " ") + "…"
        : Content.Replace("\n", " ");

    public event PropertyChangedEventHandler? PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string? n = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(n));
}
