"use client";

import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { Loader2 as Loader, KeyRound } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardBody, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";

type ApiKey = {
  id: string;
  name: string;
  keyPrefix: string;
  scopes: string[];
  status: string;
  createdAt: string;
};

export default function ApiKeysPage() {
  const [keys, setKeys] = useState<ApiKey[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [revealed, setRevealed] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    const res = await fetch("/api/settings/api-keys");
    const j = await res.json().catch(() => ({}));
    if (res.ok) setKeys(j.keys ?? []);
    else toast.error(j.error ?? "Failed to load API keys.");
    setLoading(false);
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  async function create(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setSaving(true);
    const data: Record<string, string> = {};
    for (const [k, v] of new FormData(e.currentTarget).entries()) data[k] = String(v);
    const res = await fetch("/api/settings/api-keys", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name: data.name, scopes: ["messages", "contacts"] }),
    });
    const j = await res.json().catch(() => ({}));
    setSaving(false);
    if (!res.ok) return toast.error(j.error ?? "Create failed.");
    setRevealed(j.key as string);
    e.currentTarget.reset();
    load();
  }

  async function revoke(id: string) {
    if (!confirm("Revoke this API key? This cannot be undone.")) return;
    const res = await fetch("/api/settings/api-keys", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id, status: "REVOKED" }),
    });
    if (!res.ok) return toast.error("Revoke failed.");
    toast.success("Key revoked.");
    load();
  }

  return (
    <div className="max-w-2xl space-y-4">
      <Card>
        <CardHeader>
          <CardTitle>Create API key</CardTitle>
        </CardHeader>
        <CardBody>
          {revealed && (
            <div className="mb-4 rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800">
              <p className="font-semibold">Key created — copy it now. It will not be shown again.</p>
              <code className="mt-1 block break-all rounded bg-card px-2 py-1 font-mono text-xs">{revealed}</code>
            </div>
          )}
          <form onSubmit={create} className="flex gap-2">
            <Input name="name" placeholder="e.g. Production messenger" required className="flex-1" />
            <Button type="submit" loading={saving}>
              <KeyRound className="h-4 w-4" /> Create
            </Button>
          </form>
          <p className="mt-3 text-xs text-muted-foreground">
            Keys authenticate requests to the public API at <code className="rounded bg-muted px-1">/api/v1/*</code>{" "}
            using the <code className="rounded bg-muted px-1">Authorization: Bearer</code> header.
          </p>
        </CardBody>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Active keys</CardTitle>
        </CardHeader>
        <CardBody>
          {loading ? (
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <Loader className="h-4 w-4 animate-spin" /> Loading…
            </div>
          ) : keys.length === 0 ? (
            <p className="text-sm text-muted-foreground">No API keys yet.</p>
          ) : (
            <div className="space-y-3">
              {keys.map((k) => (
                <div key={k.id} className="flex items-center gap-3 rounded-lg border border-border px-4 py-3">
                  <div className="min-w-0 flex-1">
                    <p className="flex items-center gap-2 text-sm font-semibold text-foreground">
                      {k.name}
                      <Badge tone={k.status === "ACTIVE" ? "green" : "red"}>{k.status}</Badge>
                    </p>
                    <p className="mt-0.5 font-mono text-xs text-muted-foreground">wacrm_live_{k.keyPrefix}…</p>
                  </div>
                  {k.status === "ACTIVE" && (
                    <Button variant="outline" size="sm" onClick={() => revoke(k.id)}>
                      Revoke
                    </Button>
                  )}
                </div>
              ))}
            </div>
          )}
        </CardBody>
      </Card>
    </div>
  );
}
