"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";

type ApiKey = {
  id: string;
  name: string;
  lastUsedAt: string | null;
  createdAt: string;
};

type CreateApiKeyResponse = {
  id: string;
  name: string;
  key: string;
  createdAt: string;
};

function formatDate(iso: string) {
  return new Date(iso).toLocaleDateString(undefined, {
    year: "numeric",
    month: "short",
    day: "numeric",
  });
}

export function ApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) {
  const t = useTranslations("settingsForm");
  const [keys, setKeys] = useState<ApiKey[]>(initialKeys);
  const [name, setName] = useState("");
  const [creating, setCreating] = useState(false);
  const [newKey, setNewKey] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    if (!name.trim()) return;
    setCreating(true);
    try {
      const res = await fetch("/api/v1/api-keys", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: name.trim() }),
      });
      if (!res.ok) {
        const data = await res.json() as { error?: string };
        throw new Error(data.error ?? t("apiKeyCreateFailed"));
      }
      const data = await res.json() as CreateApiKeyResponse;
      setNewKey(data.key);
      setKeys((prev) => [
        { id: data.id, name: data.name, lastUsedAt: null, createdAt: data.createdAt },
        ...prev,
      ]);
      setName("");
    } catch (err) {
      toast.error(err instanceof Error ? err.message : t("apiKeyCreateFailed"));
    } finally {
      setCreating(false);
    }
  }

  async function handleRevoke(id: string) {
    try {
      const res = await fetch(`/api/v1/api-keys/${id}`, { method: "DELETE" });
      if (!res.ok) {
        const data = await res.json() as { error?: string };
        throw new Error(data.error ?? t("apiKeyRevokeFailed"));
      }
      setKeys((prev) => prev.filter((k) => k.id !== id));
    } catch (err) {
      toast.error(err instanceof Error ? err.message : t("apiKeyRevokeFailed"));
    }
  }

  async function handleCopy() {
    if (!newKey) return;
    try {
      await navigator.clipboard.writeText(newKey);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      toast.error(t("copyFailed"));
    }
  }

  return (
    <div className="space-y-8">
      {/* Create form */}
      <form onSubmit={handleCreate} className="space-y-4">
        <div className="space-y-2">
          <Label htmlFor="key-name">{t("apiKeyNameLabel")}</Label>
          <div className="flex gap-2">
            <Input
              id="key-name"
              placeholder={t("apiKeyNamePlaceholder")}
              value={name}
              onChange={(e) => setName(e.target.value)}
              maxLength={100}
              required
            />
            <Button type="submit" disabled={creating || !name.trim()}>
              {creating ? t("apiKeyCreating") : t("apiKeyCreate")}
            </Button>
          </div>
        </div>
      </form>

      {/* New key reveal */}
      {newKey && (
        <div className="rounded-md border border-yellow-400 bg-yellow-50 p-4 space-y-3 dark:bg-yellow-950 dark:border-yellow-700">
          <p className="text-sm font-medium text-yellow-800 dark:text-yellow-200">
            {t("apiKeyRevealNotice")}
          </p>
          <div className="flex items-center gap-2">
            <code className="flex-1 rounded bg-white dark:bg-black border px-3 py-2 text-sm font-mono break-all">
              {newKey}
            </code>
            <Button type="button" variant="outline" onClick={handleCopy}>
              {copied ? t("copied") : t("copy")}
            </Button>
          </div>
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={() => setNewKey(null)}
            className="text-muted-foreground"
          >
            {t("dismiss")}
          </Button>
        </div>
      )}

      {/* Keys list */}
      {keys.length === 0 ? (
        <p className="text-sm text-muted-foreground">{t("noApiKeys")}</p>
      ) : (
        <div className="divide-y rounded-md border">
          {keys.map((k) => (
            <div key={k.id} className="flex items-center justify-between px-4 py-3 gap-4">
              <div className="min-w-0 flex-1 space-y-1">
                <p className="text-sm font-medium truncate">{k.name}</p>
                <div className="flex items-center gap-2 text-xs text-muted-foreground">
                  <span>{t("createdOn", { date: formatDate(k.createdAt) })}</span>
                  <span>·</span>
                  {k.lastUsedAt ? (
                    <span>{t("lastUsedOn", { date: formatDate(k.lastUsedAt) })}</span>
                  ) : (
                    <Badge variant="secondary" className="text-xs">{t("neverUsed")}</Badge>
                  )}
                </div>
              </div>
              <Button
                type="button"
                variant="destructive"
                size="sm"
                onClick={() => { void handleRevoke(k.id); }}
              >
                {t("revoke")}
              </Button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
