"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";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";

type ApiKeyScope = "full" | "read";

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

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

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

function formatDateTime(iso: string) {
  return new Date(iso).toLocaleString(undefined, {
    year: "numeric",
    month: "short",
    day: "numeric",
    hour: "numeric",
    minute: "2-digit",
  });
}

export function ApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) {
  const t = useTranslations("settingsForm");
  const [keys, setKeys] = useState<ApiKey[]>(initialKeys);
  const [name, setName] = useState("");
  const [scope, setScope] = useState<ApiKeyScope>("full");
  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(), scope }),
      });
      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, scope: data.scope, lastUsedAt: null, createdAt: data.createdAt },
        ...prev,
      ]);
      setName("");
      setScope("full");
    } 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
            />
            <Select value={scope} onValueChange={(v) => setScope(v as ApiKeyScope)}>
              <SelectTrigger className="w-36">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="full">{t("apiKeyScopeFull")}</SelectItem>
                <SelectItem value="read">{t("apiKeyScopeRead")}</SelectItem>
              </SelectContent>
            </Select>
            <Button type="submit" disabled={creating || !name.trim()}>
              {creating ? t("apiKeyCreating") : t("apiKeyCreate")}
            </Button>
          </div>
          <p className="text-xs text-muted-foreground">{t("apiKeyScopeHelp")}</p>
        </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">
                <div className="flex items-center gap-2">
                  <p className="text-sm font-medium truncate">{k.name}</p>
                  <Badge variant={k.scope === "read" ? "secondary" : "default"} className="text-xs">
                    {k.scope === "read" ? t("apiKeyScopeRead") : t("apiKeyScopeFull")}
                  </Badge>
                </div>
                <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: formatDateTime(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>
  );
}
