import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import {
  getApiKeys, addApiKey, editApiKey, deleteApiKey,
  type ApiKey, type SaveApiKeyInput,
} from "../../lib/commands";

const PROVIDERS = [
  { value: "deepseek", label: "DeepSeek", color: "bg-blue-100 text-blue-700 border-blue-200" },
  { value: "openai", label: "OpenAI", color: "bg-emerald-100 text-emerald-700 border-emerald-200" },
  { value: "anthropic", label: "Anthropic", color: "bg-orange-100 text-orange-700 border-orange-200" },
  { value: "google", label: "Google", color: "bg-red-100 text-red-700 border-red-200" },
  { value: "zhipu", label: "智谱", color: "bg-purple-100 text-purple-700 border-purple-200" },
  { value: "moonshot", label: "月之暗面", color: "bg-indigo-100 text-indigo-700 border-indigo-200" },
  { value: "qwen", label: "通义千问", color: "bg-cyan-100 text-cyan-700 border-cyan-200" },
  { value: "custom", label: "自定义", color: "bg-gray-100 text-gray-600 border-gray-200" },
];

function getProviderStyle(provider: string) {
  return PROVIDERS.find((p) => p.value === provider)?.color ?? PROVIDERS[PROVIDERS.length - 1].color;
}
function getProviderLabel(provider: string) {
  return PROVIDERS.find((p) => p.value === provider)?.label ?? provider;
}

function CopyBtn({ value }: { value: string }) {
  const [copied, setCopied] = useState(false);
  const handleCopy = async () => {
    await navigator.clipboard.writeText(value);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };
  return (
    <button onClick={handleCopy}
      className="shrink-0 px-1.5 py-0.5 rounded text-[11px] border border-gray-200 text-gray-400 hover:text-blue-500 hover:border-blue-300 hover:bg-blue-50 transition-colors">
      {copied ? "已复制" : "复制"}
    </button>
  );
}

// ── 模态框表单 ────────────────────────────────────────────────────────────────

function ApiKeyModal({ initial, onSave, onClose, saving }: {
  initial?: ApiKey;
  onSave: (input: SaveApiKeyInput) => void;
  onClose: () => void;
  saving: boolean;
}) {
  const [name, setName] = useState(initial?.name ?? "");
  const [provider, setProvider] = useState(initial?.provider ?? "deepseek");
  const [apiKey, setApiKey] = useState(initial?.api_key ?? "");
  const [baseUrl, setBaseUrl] = useState(initial?.base_url ?? "");
  const [model, setModel] = useState(initial?.model ?? "");
  const [notes, setNotes] = useState(initial?.notes ?? "");

  const handleSubmit = () => {
    if (!name.trim() || !apiKey.trim()) return;
    onSave({
      name: name.trim(),
      provider,
      api_key: apiKey.trim(),
      base_url: baseUrl.trim() || undefined,
      model: model.trim() || undefined,
      notes: notes.trim() || undefined,
    });
  };

  const isEdit = !!initial;

  return (
    <div className="fixed inset-0 bg-black/30 z-50 flex items-center justify-center" onClick={onClose}>
      <div className="bg-white rounded-xl border border-gray-200 shadow-xl w-[520px] flex flex-col" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100">
          <h3 className="text-sm font-bold text-gray-800">{isEdit ? "编辑 API Key" : "添加 API Key"}</h3>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600 text-lg leading-none">x</button>
        </div>

        <div className="px-6 py-4 space-y-3">
          <div className="grid grid-cols-[72px_1fr] gap-x-3 gap-y-2.5 items-center">
            <label className="text-[11px] text-gray-400 text-right">名称 *</label>
            <input value={name} onChange={(e) => setName(e.target.value)} placeholder="例: DeepSeek 主账号"
              className="text-xs px-2.5 py-2 rounded border border-gray-200 bg-gray-50 focus:outline-none focus:border-blue-300" />
            <label className="text-[11px] text-gray-400 text-right">服务商</label>
            <select value={provider} onChange={(e) => setProvider(e.target.value)}
              className="text-xs px-2.5 py-2 rounded border border-gray-200 bg-gray-50 focus:outline-none focus:border-blue-300 w-40">
              {PROVIDERS.map((p) => <option key={p.value} value={p.value}>{p.label}</option>)}
            </select>
            <label className="text-[11px] text-gray-400 text-right">API Key *</label>
            <input value={apiKey} onChange={(e) => setApiKey(e.target.value)} placeholder="sk-..."
              className="text-xs px-2.5 py-2 rounded border border-gray-200 bg-gray-50 focus:outline-none focus:border-blue-300 font-mono" />
            <label className="text-[11px] text-gray-400 text-right">Base URL</label>
            <input value={baseUrl} onChange={(e) => setBaseUrl(e.target.value)} placeholder="https://api.deepseek.com"
              className="text-xs px-2.5 py-2 rounded border border-gray-200 bg-gray-50 focus:outline-none focus:border-blue-300 font-mono" />
            <label className="text-[11px] text-gray-400 text-right">模型</label>
            <input value={model} onChange={(e) => setModel(e.target.value)} placeholder="例: deepseek-chat"
              className="text-xs px-2.5 py-2 rounded border border-gray-200 bg-gray-50 focus:outline-none focus:border-blue-300 font-mono" />
            <label className="text-[11px] text-gray-400 text-right self-start mt-2">备注</label>
            <div className="space-y-1">
              <textarea value={notes} onChange={(e) => setNotes(e.target.value)}
                placeholder={"支持 Markdown 语法，例如：\n# 使用方式\n- `export API_KEY=\"sk-xxx\"`\n- 启用 provider"} rows={4}
                className="w-full text-xs px-2.5 py-2 rounded border border-gray-200 bg-gray-50 focus:outline-none focus:border-blue-300 resize-y min-h-[72px] font-mono" />
              <span className="text-[10px] text-gray-300">支持 Markdown：标题、列表、代码块、表格等</span>
            </div>
          </div>
        </div>

        <div className="flex items-center justify-end gap-2 px-6 py-3 border-t border-gray-100 bg-gray-50/50">
          <button onClick={onClose}
            className="px-3 py-1.5 rounded-md text-xs border border-gray-200 text-gray-500 hover:bg-gray-50 transition-colors">
            取消
          </button>
          <button onClick={handleSubmit} disabled={saving || !name.trim() || !apiKey.trim()}
            className="px-4 py-1.5 rounded-md text-xs font-medium bg-blue-600 text-white hover:bg-blue-700 transition-colors disabled:opacity-40">
            {saving ? "保存中…" : "保存"}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── API Key 卡片 ──────────────────────────────────────────────────────────────

function ApiKeyCard({ item, onEdit, onDelete }: {
  item: ApiKey;
  onEdit: () => void;
  onDelete: () => void;
}) {
  const [showKey, setShowKey] = useState(false);
  const [confirmDelete, setConfirmDelete] = useState(false);

  const maskedKey = item.api_key.length > 8
    ? item.api_key.slice(0, 4) + "••••••••" + item.api_key.slice(-4)
    : "••••••••";

  return (
    <div className="bg-white border border-gray-200 rounded-xl overflow-hidden shadow-sm">
      {/* 标题栏 */}
      <div className="flex items-center gap-3 px-5 py-3 bg-gradient-to-r from-gray-50 to-white border-b border-gray-100">
        <span className={`text-[10px] px-2 py-0.5 rounded border font-medium ${getProviderStyle(item.provider)}`}>
          {getProviderLabel(item.provider)}
        </span>
        <span className="text-sm font-bold text-gray-800 flex-1 min-w-0 truncate">{item.name}</span>
        <div className="flex gap-1.5 shrink-0">
          <button onClick={onEdit}
            className="px-2.5 py-1 rounded-md text-[11px] border border-gray-200 text-gray-500 hover:bg-gray-50 transition-colors">
            编辑
          </button>
          {!confirmDelete ? (
            <button onClick={() => setConfirmDelete(true)}
              className="px-2.5 py-1 rounded-md text-[11px] border border-gray-200 text-gray-400 hover:text-red-500 hover:border-red-200 transition-colors">
              删除
            </button>
          ) : (
            <div className="flex gap-1">
              <button onClick={onDelete}
                className="px-2.5 py-1 rounded-md text-[11px] border border-red-300 bg-red-50 text-red-600 hover:bg-red-100 transition-colors">
                确认
              </button>
              <button onClick={() => setConfirmDelete(false)}
                className="px-2.5 py-1 rounded-md text-[11px] border border-gray-200 text-gray-400 transition-colors">
                取消
              </button>
            </div>
          )}
        </div>
      </div>

      {/* 备注 (Markdown) */}
      {item.notes && (
        <div className="px-5 py-2.5 border-b border-gray-100 bg-gray-50/60">
          <div className="prose prose-xs prose-gray max-w-none
            [&_p]:text-xs [&_p]:leading-relaxed [&_p]:my-1
            [&_h1]:text-sm [&_h2]:text-xs [&_h3]:text-xs
            [&_h1]:font-bold [&_h2]:font-semibold [&_h3]:font-medium
            [&_h1]:my-1.5 [&_h2]:my-1 [&_h3]:my-1
            [&_ul]:text-xs [&_ol]:text-xs [&_ul]:my-1 [&_ol]:my-1 [&_li]:my-0.5
            [&_code]:text-[11px] [&_code]:bg-gray-100 [&_code]:px-1 [&_code]:py-0.5 [&_code]:rounded
            [&_pre]:text-[11px] [&_pre]:bg-gray-100 [&_pre]:rounded-md [&_pre]:p-2 [&_pre]:my-1.5 [&_pre]:overflow-x-auto
            [&_table]:text-xs [&_th]:px-2 [&_th]:py-1 [&_td]:px-2 [&_td]:py-1
            [&_a]:text-blue-500 [&_a]:no-underline hover:[&_a]:underline
            [&_blockquote]:text-xs [&_blockquote]:border-l-2 [&_blockquote]:border-gray-300 [&_blockquote]:pl-3 [&_blockquote]:my-1 [&_blockquote]:text-gray-500">
            <ReactMarkdown remarkPlugins={[remarkGfm]}>{item.notes}</ReactMarkdown>
          </div>
        </div>
      )}

      {/* 内容 */}
      <div className="px-5 py-3 space-y-1.5">
        {/* API Key */}
        <div className="flex items-center gap-3">
          <span className="text-[11px] text-gray-400 w-16 shrink-0 text-right">API Key</span>
          <span className="text-xs font-mono text-gray-700 flex-1 min-w-0 truncate">
            {showKey ? item.api_key : maskedKey}
          </span>
          <button onClick={() => setShowKey((v) => !v)}
            className="text-[10px] text-gray-400 hover:text-gray-600 transition-colors shrink-0">
            {showKey ? "隐藏" : "显示"}
          </button>
          <CopyBtn value={item.api_key} />
        </div>

        {/* Base URL */}
        {item.base_url && (
          <div className="flex items-center gap-3">
            <span className="text-[11px] text-gray-400 w-16 shrink-0 text-right">Base URL</span>
            <span className="text-xs font-mono text-gray-700 flex-1 min-w-0 truncate">{item.base_url}</span>
            <CopyBtn value={item.base_url} />
          </div>
        )}

        {/* Model */}
        {item.model && (
          <div className="flex items-center gap-3">
            <span className="text-[11px] text-gray-400 w-16 shrink-0 text-right">模型</span>
            <span className="text-xs font-mono text-gray-700">{item.model}</span>
            <CopyBtn value={item.model} />
          </div>
        )}
      </div>
    </div>
  );
}

// ── 主面板 ────────────────────────────────────────────────────────────────────

export function ApiKeysPanel() {
  const qc = useQueryClient();
  const [showModal, setShowModal] = useState(false);
  const [editingItem, setEditingItem] = useState<ApiKey | null>(null);

  const { data: keys = [] } = useQuery({
    queryKey: ["api-keys"],
    queryFn: getApiKeys,
  });

  const addMut = useMutation({
    mutationFn: (input: SaveApiKeyInput) => addApiKey(input),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["api-keys"] }); setShowModal(false); },
  });

  const editMut = useMutation({
    mutationFn: ({ id, input }: { id: string; input: SaveApiKeyInput }) => editApiKey(id, input),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["api-keys"] }); setEditingItem(null); },
  });

  const deleteMut = useMutation({
    mutationFn: (id: string) => deleteApiKey(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["api-keys"] }),
  });

  return (
    <div className="space-y-4">
      {/* 顶部操作栏 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <h2 className="text-sm font-bold text-gray-700">密钥凭据</h2>
          <span className="text-xs text-gray-400 bg-gray-100 rounded-full px-2 py-0.5">
            {keys.length} 个
          </span>
          <span className="text-[11px] text-gray-400">API Key / Token / 密码等各类凭据统一存放</span>
        </div>
        <button onClick={() => setShowModal(true)}
          className="px-3 py-1.5 rounded-md text-xs font-medium border border-blue-300 bg-blue-50 text-blue-600 hover:bg-blue-100 transition-colors">
          + 添加凭据
        </button>
      </div>

      {/* 列表 */}
      {keys.length === 0 && (
        <div className="text-center py-24 text-gray-400">
          <p className="text-4xl mb-4">🔑</p>
          <p className="text-sm">还没有 API Key，点击「+ 添加 API Key」开始管理</p>
          <p className="text-xs text-gray-300 mt-1">支持 DeepSeek、OpenAI、Anthropic 等主流服务商</p>
        </div>
      )}

      {keys.map((k) => (
        <ApiKeyCard
          key={k.id}
          item={k}
          onEdit={() => setEditingItem(k)}
          onDelete={() => deleteMut.mutate(k.id)}
        />
      ))}

      {showModal && (
        <ApiKeyModal
          onSave={(input) => addMut.mutate(input)}
          onClose={() => setShowModal(false)}
          saving={addMut.isPending}
        />
      )}

      {editingItem && (
        <ApiKeyModal
          initial={editingItem}
          onSave={(input) => editMut.mutate({ id: editingItem.id, input })}
          onClose={() => setEditingItem(null)}
          saving={editMut.isPending}
        />
      )}
    </div>
  );
}
