'use client';
import { useState } from 'react';

/** B2B API anahtarı: üret / göster / iptal. Anahtar yalnızca üretildiği an tam görünür. */
export function ApiKeyPanel({ hasKey, appUrl }: { hasKey: boolean; appUrl: string }) {
  const [key, setKey] = useState<string | null>(null);
  const [active, setActive] = useState(hasKey);
  const [busy, setBusy] = useState(false);
  const [copied, setCopied] = useState(false);

  async function gen() {
    if (active && !confirm('Yeni anahtar üretilince eski anahtar çalışmaz. Devam edilsin mi?')) return;
    setBusy(true);
    const r = await fetch('/api/hesap/apikey', { method: 'POST' });
    const j = await r.json().catch(() => ({}));
    setBusy(false);
    if (r.ok) { setKey(j.key); setActive(true); }
  }
  async function revoke() {
    if (!confirm('Anahtar iptal edilsin mi? Bu anahtarla yapılan entegrasyonlar çalışmayı durdurur.')) return;
    setBusy(true);
    await fetch('/api/hesap/apikey', { method: 'DELETE' });
    setBusy(false); setKey(null); setActive(false);
  }
  const curl = `curl -X POST ${appUrl}/api/v1/orders \\\n  -H "Authorization: Bearer ${key || 'ps_ANAHTARINIZ'}" \\\n  -H "Content-Type: application/json" \\\n  -d '{"il":"Muğla","ilce":"Ula","mahalle":"Gökova","mahalleId":137536,"ada":"101","parsel":"5","template":"prestij"}'`;

  return (
    <div className="space-y-3">
      <p className="text-[13.5px] text-ink-soft">Kendi sisteminizden (CRM, portföy yazılımı) programatik olarak video siparişi vermek için. Her sipariş 1 kredi düşer.</p>
      {key && (
        <div className="bg-signal-soft p-3">
          <div className="label mb-1">Yeni anahtarınız · bir daha gösterilmez</div>
          <div className="flex items-center gap-2 border border-ink/25 bg-white p-1 pl-2.5">
            <code className="min-w-0 flex-1 truncate text-[13px]">{key}</code>
            <button type="button" onClick={() => { navigator.clipboard.writeText(key).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1600); }); }} className="btn-ink btn-sm shrink-0">{copied ? 'Kopyalandı' : 'Kopyala'}</button>
          </div>
        </div>
      )}
      <div className="flex flex-wrap gap-2">
        <button type="button" onClick={gen} disabled={busy} className="btn-ink btn-sm">{active ? 'Yeni anahtar üret' : 'Anahtar oluştur'}</button>
        {active && <button type="button" onClick={revoke} disabled={busy} className="btn-line btn-sm">İptal et</button>}
      </div>
      {active && !key && <p className="text-[12.5px] text-ink-soft">Etkin bir anahtarınız var. Anahtarın tamamı yalnızca üretildiği an gösterilir; kaybettiyseniz yenisini üretin.</p>}
      <details className="text-[13px]">
        <summary className="cursor-pointer font-semibold">Örnek istek</summary>
        <pre className="mt-2 overflow-x-auto bg-ink p-3 text-[12px] leading-relaxed text-white"><code>{curl}</code></pre>
        <p className="mt-1 text-[12px] text-ink-soft">Yanıttaki <code>statusUrl</code> adresini çağırarak sipariş durumunu ve teslim edilince izleme bağlantısını alırsınız.</p>
      </details>
    </div>
  );
}
