"use client";

import { useState } from "react";
import { API_DOCS_URL } from "@/lib/plans";

type Props = {
  initialStatus: { configured: boolean; prefix: string | null };
  initialRateLimit: {
    limit: number;
    used: number;
    remaining: number;
    windowSeconds: number;
    resetsInSeconds: number;
  };
};

export function ApiKeySettings({ initialStatus, initialRateLimit }: Props) {
  const [status, setStatus] = useState(initialStatus);
  const [newKey, setNewKey] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function generateKey() {
    if (status.configured && !confirm("Replace your existing API key?")) return;
    setLoading(true);
    setError(null);
    setNewKey(null);
    try {
      const res = await fetch("/api/account/api-key", { method: "POST" });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to generate API key");
      setNewKey(data.apiKey);
      setStatus({ configured: true, prefix: data.prefix });
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to generate API key");
    } finally {
      setLoading(false);
    }
  }

  async function revokeKey() {
    if (!confirm("Revoke your API key?")) return;
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/account/api-key", { method: "DELETE" });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to revoke API key");
      setStatus({ configured: false, prefix: null });
      setNewKey(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to revoke API key");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="space-y-4">
      <p className="text-sm text-gray-400">
        Use the REST API to upload files and create video jobs programmatically.
      </p>
      <p className="text-xs text-gray-500">
        Rate limit: {initialRateLimit.limit} requests per {initialRateLimit.windowSeconds} seconds.
      </p>
      {status.configured && status.prefix && (
        <p className="text-sm text-gray-300">
          Active key: <span className="font-mono text-white">{status.prefix}…</span>
        </p>
      )}
      {newKey && (
        <div className="rounded border border-green-500/40 bg-green-500/10 p-4">
          <p className="mb-2 text-sm font-medium text-green-300">Copy your new API key now</p>
          <code className="block break-all rounded bg-black/40 px-3 py-2 text-xs text-green-200">
            {newKey}
          </code>
        </div>
      )}
      {error && <p className="text-sm text-red-300">{error}</p>}
      <div className="flex flex-wrap gap-3">
        <button
          type="button"
          onClick={generateKey}
          disabled={loading}
          className="rounded bg-accent px-4 py-2 text-sm font-medium text-white hover:bg-accent-hover disabled:opacity-50"
        >
          {loading ? "Working…" : status.configured ? "Regenerate API key" : "Generate API key"}
        </button>
        {status.configured && (
          <button
            type="button"
            onClick={revokeKey}
            disabled={loading}
            className="rounded border border-red-600/50 px-4 py-2 text-sm font-medium text-red-300 hover:bg-red-500/10"
          >
            Revoke API key
          </button>
        )}
        <a
          href={API_DOCS_URL}
          target="_blank"
          rel="noopener noreferrer"
          className="rounded border border-gray-600 px-4 py-2 text-sm text-gray-300 hover:text-white"
        >
          API documentation
        </a>
      </div>
    </div>
  );
}
