"use client";

import { useState, useEffect, useCallback } from "react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { DataTable, type Column } from "@/components/ui/data-table";
import { Key, Plus, Copy, Trash2, AlertTriangle } from "lucide-react";

interface ApiKeyRow {
  id: string;
  name: string;
  prefix: string;
  lastUsed: string | null;
  createdAt: string;
}

interface NewKeyResponse {
  id: string;
  name: string;
  key: string;
  prefix: string;
  createdAt: string;
}

export default function ApiKeysPage() {
  const [keys, setKeys] = useState<ApiKeyRow[]>([]);
  const [limit, setLimit] = useState<number | null>(null);
  const [loading, setLoading] = useState(true);
  const [newKeyName, setNewKeyName] = useState("");
  const [creating, setCreating] = useState(false);
  const [newKey, setNewKey] = useState<NewKeyResponse | null>(null);
  const [copied, setCopied] = useState(false);
  const [error, setError] = useState("");

  const fetchKeys = useCallback(async () => {
    try {
      const res = await fetch("/api/keys");
      if (res.ok) {
        const data = await res.json();
        setKeys(data.keys ?? []);
        setLimit(typeof data.limit === "number" ? data.limit : null);
      }
    } catch {
      setError("Failed to load API keys");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchKeys();
  }, [fetchKeys]);

  const createKey = async () => {
    if (!newKeyName.trim()) return;
    setCreating(true);
    setError("");

    try {
      const res = await fetch("/api/keys", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: newKeyName.trim() }),
      });

      if (!res.ok) {
        const data = await res.json();
        setError(data.error || "Failed to create key");
        return;
      }

      const data = await res.json();
      setNewKey(data);
      setNewKeyName("");
      fetchKeys();
    } catch {
      setError("Failed to create key");
    } finally {
      setCreating(false);
    }
  };

  const revokeKey = async (id: string) => {
    try {
      const res = await fetch(`/api/keys/${id}`, { method: "DELETE" });
      if (res.ok) {
        fetchKeys();
      } else {
        const data = await res.json();
        setError(data.error || "Failed to revoke key");
      }
    } catch {
      setError("Failed to revoke key");
    }
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const columns: Column<ApiKeyRow>[] = [
    { key: "name", header: "Name" },
    {
      key: "prefix",
      header: "Key",
      render: (row) => (
        <code className="rounded bg-gray-800 px-2 py-1 text-xs text-gray-300">
          {row.prefix}
        </code>
      ),
    },
    {
      key: "createdAt",
      header: "Created",
      render: (row) => new Date(row.createdAt).toLocaleDateString(),
    },
    {
      key: "lastUsed",
      header: "Last Used",
      render: (row) =>
        row.lastUsed
          ? new Date(row.lastUsed).toLocaleDateString()
          : "Never",
    },
  ];

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-white">API Keys</h1>
        <p className="mt-1 text-sm text-gray-400">
          {limit != null
            ? `${keys.length} of ${limit} API keys used. `
            : ""}
          Manage API keys for programmatic access to LLMHosts.
        </p>
      </div>

      {error && (
        <div className="flex items-center gap-2 rounded-lg border border-red-800/50 bg-red-900/20 px-4 py-3 text-sm text-red-400">
          <AlertTriangle size={16} />
          {error}
          <button
            onClick={() => setError("")}
            className="ml-auto text-red-400 hover:text-red-300"
          >
            Dismiss
          </button>
        </div>
      )}

      {/* New key reveal banner */}
      {newKey && (
        <div className="rounded-lg border border-emerald-800/50 bg-emerald-900/20 p-4">
          <div className="flex items-start gap-3">
            <Key className="mt-0.5 h-5 w-5 text-emerald-400" />
            <div className="flex-1">
              <p className="text-sm font-medium text-emerald-300">
                API key created: {newKey.name}
              </p>
              <p className="mt-1 text-xs text-emerald-400/70">
                Copy this key now. You won&apos;t be able to see it again.
              </p>
              <div className="mt-2 flex items-center gap-2">
                <code className="flex-1 rounded bg-gray-900 px-3 py-2 text-sm text-gray-200 font-mono break-all">
                  {newKey.key}
                </code>
                <Button
                  variant={copied ? "primary" : "secondary"}
                  size="sm"
                  onClick={() => copyToClipboard(newKey.key)}
                >
                  <Copy size={14} />
                  {copied ? "Copied" : "Copy"}
                </Button>
              </div>
            </div>
            <button
              onClick={() => setNewKey(null)}
              className="text-emerald-400/50 hover:text-emerald-300"
            >
              Dismiss
            </button>
          </div>
        </div>
      )}

      {/* Create new key */}
      <Card title="Create API Key" icon={<Plus size={20} />}>
        <div className="flex gap-3">
          <div className="flex-1">
            <Input
              label=""
              placeholder="Key name (e.g. Production, CI/CD)"
              value={newKeyName}
              onChange={(e) => setNewKeyName(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && createKey()}
            />
          </div>
          <Button
            variant="primary"
            size="sm"
            onClick={createKey}
            disabled={creating || !newKeyName.trim()}
            className="self-end"
          >
            {creating ? "Creating..." : "Create Key"}
          </Button>
        </div>
        <p className="mt-2 text-xs text-gray-500">
          Keys grant full access to your LLMHosts proxy. Keep them secret.
        </p>
      </Card>

      {/* Keys table */}
      <Card title="Active Keys" icon={<Key size={20} />}>
        {loading ? (
          <p className="py-8 text-center text-sm text-gray-500">Loading...</p>
        ) : (
          <DataTable
            columns={columns}
            data={keys}
            keyExtractor={(row) => row.id}
            emptyMessage="No API keys yet. Create one above."
            actions={(row) => (
              <Button
                variant="danger"
                size="sm"
                onClick={() => revokeKey(row.id)}
              >
                <Trash2 size={14} />
                Revoke
              </Button>
            )}
          />
        )}
      </Card>

      {/* Usage instructions */}
      <Card title="Usage" description="Use your API key with curl or any OpenAI-compatible client">
        <div className="space-y-3 font-mono text-sm">
          <div className="rounded bg-gray-800/50 p-3">
            <p className="text-xs text-gray-500 mb-1"># curl</p>
            <code className="text-gray-300">
              curl https://llmhosts.com/v1/chat/completions \<br />
              &nbsp;&nbsp;-H &quot;Authorization: Bearer lh_sk_...&quot; \<br />
              &nbsp;&nbsp;-H &quot;Content-Type: application/json&quot; \<br />
              &nbsp;&nbsp;-d &apos;{`{"model":"llama3.2","messages":[{"role":"user","content":"Hello"}]}`}&apos;
            </code>
          </div>
          <div className="rounded bg-gray-800/50 p-3">
            <p className="text-xs text-gray-500 mb-1"># Python (OpenAI SDK)</p>
            <code className="text-gray-300">
              from openai import OpenAI<br />
              client = OpenAI(base_url=&quot;https://llmhosts.com/v1&quot;, api_key=&quot;lh_sk_...&quot;)
            </code>
          </div>
        </div>
      </Card>
    </div>
  );
}
