"use client";

import { useState } from "react";
import { Spinner } from "@/components/common/Spinner";

type ApiKey = {
  id: string;
  label: string;
  keyPrefix: string;
  scope: "READ" | "READ_WRITE" | "ADMIN";
  isActive: boolean;
  lastUsedAt: string | null;
  usageCount: number;
  expiresAt: string | null;
  createdAt: string;
};

function fmtDate(iso: string | null) {
  if (!iso) return "—";
  return new Date(iso).toLocaleDateString("sr-RS", { day: "2-digit", month: "2-digit", year: "numeric" });
}

export function PortalApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) {
  const [keys, setKeys] = useState(initialKeys);
  const [label, setLabel] = useState("");
  const [scope, setScope] = useState<"READ" | "READ_WRITE">("READ");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [newPlain, setNewPlain] = useState<string | null>(null);

  async function create() {
    if (label.trim().length < 2) {
      setError("Naziv ključa mora imati 2+ znaka.");
      return;
    }
    setBusy(true);
    setError(null);
    setNewPlain(null);
    try {
      const res = await fetch("/api/portal/api-keys", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ label, scope }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data?.error || "Greška");

      // Dodaj u listu (bez plain), prikaži plain modalom.
      setKeys((prev) => [
        {
          id: data.key.id,
          label: data.key.label,
          keyPrefix: data.key.keyPrefix,
          scope: data.key.scope,
          isActive: true,
          lastUsedAt: null,
          usageCount: 0,
          expiresAt: null,
          createdAt: data.key.createdAt,
        },
        ...prev,
      ]);
      setNewPlain(data.key.plain);
      setLabel("");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Greška");
    } finally {
      setBusy(false);
    }
  }

  async function revoke(id: string) {
    if (!window.confirm("Sigurno opozvati ključ? Aplikacije koje ga koriste će prestati da rade.")) return;
    try {
      const res = await fetch("/api/portal/api-keys", {
        method: "DELETE",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ id }),
      });
      if (!res.ok) throw new Error("revoke failed");
      setKeys((prev) => prev.map((k) => (k.id === id ? { ...k, isActive: false } : k)));
    } catch (err) {
      alert(err instanceof Error ? err.message : "Greška");
    }
  }

  return (
    <div className="space-y-6">
      {/* Plain key reveal modal */}
      {newPlain && (
        <div className="rounded-2xl border border-emerald-500/40 bg-emerald-500/5 p-5">
          <p className="text-sm font-bold text-emerald-700">
            ✓ Ključ je kreiran — kopiraj ga sada!
          </p>
          <p className="mt-1 text-xs text-emerald-700/80">
            Iz bezbednosnih razloga, sirovi ključ NEĆEMO ponovo prikazati. Sačuvaj ga u .env-u
            tvoje aplikacije ili password manageru.
          </p>
          <div className="mt-3 flex gap-2">
            <code className="flex-1 break-all rounded-lg border border-emerald-500/30 bg-white px-3 py-2 font-mono text-xs text-emerald-900">
              {newPlain}
            </code>
            <button
              type="button"
              onClick={() => {
                navigator.clipboard.writeText(newPlain).catch(() => undefined);
              }}
              className="rounded-lg bg-emerald-600 px-3 py-2 text-xs font-bold text-white"
            >
              Kopiraj
            </button>
          </div>
          <button
            type="button"
            onClick={() => setNewPlain(null)}
            className="mt-3 text-xs font-semibold text-emerald-700 hover:underline"
          >
            Sakrij — sačuvao sam ključ
          </button>
        </div>
      )}

      <section className="rounded-2xl border border-zinc-800 bg-zinc-950/60 p-5">
        <h3 className="text-base font-semibold text-white">Kreiraj novi API ključ</h3>
        <p className="mt-1 text-xs text-zinc-400">
          Koristi se za eksterne integracije sa CRM-ovima, marketing alatima i partnerskim portalima.
          Maksimalno 10 aktivnih ključeva po firmi.
        </p>
        <div className="mt-4 grid gap-3 md:grid-cols-[1fr_180px_auto]">
          <input
            value={label}
            onChange={(e) => setLabel(e.target.value)}
            placeholder='Naziv ključa (npr. "HubSpot integracija")'
            className="h-11 rounded-xl border border-zinc-700 bg-zinc-900 px-4 text-sm text-white placeholder:text-zinc-500"
          />
          <select
            value={scope}
            onChange={(e) => setScope(e.target.value as never)}
            className="h-11 rounded-xl border border-zinc-700 bg-zinc-900 px-4 text-sm text-white"
          >
            <option value="READ">Read-only</option>
            <option value="READ_WRITE">Read + write</option>
          </select>
          <button
            type="button"
            onClick={create}
            disabled={busy}
            className="inline-flex items-center justify-center gap-2 rounded-xl bg-orange-500 px-5 py-2.5 text-sm font-bold text-zinc-950 hover:bg-orange-400 disabled:opacity-50"
          >
            {busy ? <Spinner className="h-4 w-4" /> : null}
            {busy ? "Kreiram..." : "Kreiraj"}
          </button>
        </div>
        {error && (
          <p className="mt-2 rounded-lg border border-rose-500/40 bg-rose-500/10 px-3 py-2 text-xs text-rose-200">
            {error}
          </p>
        )}
      </section>

      <section className="rounded-2xl border border-zinc-800 bg-zinc-950/60 p-5">
        <h3 className="text-base font-semibold text-white">Tvoji API ključevi</h3>
        {keys.length === 0 ? (
          <p className="mt-2 text-sm text-zinc-500">Nemaš još kreirane ključeve.</p>
        ) : (
          <div className="mt-4 overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="text-xs uppercase tracking-wide text-zinc-500">
                <tr>
                  <th className="px-2 py-2 text-left">Naziv</th>
                  <th className="px-2 py-2 text-left">Prefix</th>
                  <th className="px-2 py-2 text-left">Scope</th>
                  <th className="px-2 py-2 text-left">Korišćenje</th>
                  <th className="px-2 py-2 text-left">Status</th>
                  <th className="px-2 py-2 text-left">Akcija</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-zinc-800">
                {keys.map((k) => (
                  <tr key={k.id}>
                    <td className="px-2 py-3 text-zinc-200">{k.label}</td>
                    <td className="px-2 py-3 font-mono text-xs text-zinc-400">{k.keyPrefix}…</td>
                    <td className="px-2 py-3 text-zinc-300">{k.scope}</td>
                    <td className="px-2 py-3 text-zinc-400">
                      {k.usageCount} req · {fmtDate(k.lastUsedAt)}
                    </td>
                    <td className="px-2 py-3">
                      <span
                        className={`rounded-full px-2 py-0.5 text-xs ${
                          k.isActive
                            ? "bg-emerald-500/15 text-emerald-300"
                            : "bg-zinc-700/40 text-zinc-300"
                        }`}
                      >
                        {k.isActive ? "Aktivan" : "Opozvan"}
                      </span>
                    </td>
                    <td className="px-2 py-3">
                      {k.isActive && (
                        <button
                          type="button"
                          onClick={() => revoke(k.id)}
                          className="text-xs font-semibold text-rose-400 hover:underline"
                        >
                          Opozovi
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>

      <section className="rounded-2xl border border-zinc-800 bg-zinc-950/60 p-5">
        <h3 className="text-base font-semibold text-white">Kako se koristi</h3>
        <pre className="mt-3 overflow-x-auto rounded-lg border border-zinc-800 bg-zinc-900 p-4 text-[0.8rem] leading-relaxed text-zinc-300">
{`# 1. Verifikuj ključ
curl https://biznisportal.rs/api/v1/me \\
  -H "Authorization: Bearer bp_live_TVOJ_KLJUC"

# 2. Pretraga firmi
curl "https://biznisportal.rs/api/v1/companies?q=knjigovodstvo&city=beograd" \\
  -H "Authorization: Bearer bp_live_TVOJ_KLJUC"`}
        </pre>
        <p className="mt-3 text-xs text-zinc-500">
          Rate limit: 60 zahteva/minut. Kontaktiraj nas ako ti treba više.
        </p>
      </section>
    </div>
  );
}
