"use client";

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

type ApiKeyStatus = {
  configured: boolean;
  prefix: string | null;
};

type RateLimitStatus = {
  limit: number;
  used: number;
  remaining: number;
  windowSeconds: number;
  resetsInSeconds: number;
  bonus?: number;
};

type Props = {
  initialStatus: ApiKeyStatus;
  initialRateLimit: RateLimitStatus;
};

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

  useEffect(() => {
    let active = true;
    const refresh = () => {
      fetch("/api/account/api-rate-limit")
        .then(async (res) => {
          if (!res.ok) return;
          const data = await res.json();
          if (active) setRateLimit(data);
        })
        .catch(() => {});
    };
    refresh();
    const id = setInterval(refresh, 5000);
    return () => {
      active = false;
      clearInterval(id);
    };
  }, []);

  async function generateKey() {
    if (
      status.configured &&
      !confirm("This will replace your existing API key. Continue?")
    ) {
      return;
    }

    setLoading(true);
    setError(null);
    setSuccess(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 key");
      setNewKey(data.apiKey);
      setStatus({ configured: true, prefix: data.prefix });
      setSuccess("API key generated. Copy it now — it will not be shown again.");
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to generate key");
    } finally {
      setLoading(false);
    }
  }

  async function revokeKey() {
    if (!confirm("Revoke the current API key?")) return;
    setLoading(true);
    setError(null);
    setSuccess(null);
    setNewKey(null);
    try {
      const res = await fetch("/api/account/api-key", { method: "DELETE" });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || "Failed to revoke key");
      setStatus({ configured: false, prefix: null });
      setSuccess("API key revoked.");
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to revoke 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 batch video jobs programmatically.
      </p>

      <div className="rounded border border-gray-800 bg-surface p-4 space-y-3">
        <div className="flex flex-wrap items-center justify-between gap-2">
          <p className="text-sm font-medium text-white">API rate limit</p>
          <p className="text-xs text-gray-400">Resets in {rateLimit.resetsInSeconds}s</p>
        </div>
        <p className="text-sm text-gray-300">
          {rateLimit.used} / {rateLimit.limit} requests used this minute
        </p>
        <p className="text-xs text-gray-500">
          Self-hosted: API rate limits are effectively unlimited.
        </p>
      </div>

      {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">Your new API key (copy now)</p>
          <code className="block break-all rounded bg-black/40 px-3 py-2 text-xs text-green-200">
            {newKey}
          </code>
        </div>
      )}

      {success && (
        <div className="rounded border border-green-500/40 bg-green-500/10 px-4 py-3 text-sm text-green-300">
          {success}
        </div>
      )}

      {error && (
        <div className="rounded border border-red-500/50 bg-red-500/10 px-4 py-3 text-sm text-red-300">
          {error}
        </div>
      )}

      <div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap">
        <button
          type="button"
          onClick={generateKey}
          disabled={loading}
          className="inline-flex items-center justify-center rounded bg-accent px-4 py-2 text-sm font-medium text-white transition-colors 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="inline-flex items-center justify-center rounded border border-red-600/50 px-4 py-2 text-sm font-medium text-red-300 transition-colors hover:bg-red-500/10 disabled:opacity-50"
          >
            Revoke API key
          </button>
        )}
      </div>

      <div className="rounded border border-gray-800 bg-surface p-4 text-xs text-gray-400">
        <p className="mb-2 font-semibold uppercase tracking-wider text-gray-500">Endpoints</p>
        <ul className="space-y-2 font-mono">
          <li>POST /api/v1/upload: upload image or audio file</li>
          <li>POST /api/v1/jobs: create job from paths (recommended for large batches)</li>
          <li>POST /api/v1/jobs/batch: small packs only (one-shot multipart)</li>
          <li>GET /api/v1/playlists: list YouTube playlists</li>
          <li>POST /api/v1/playlists: create a YouTube playlist</li>
          <li>GET /api/v1/jobs: list jobs</li>
          <li>GET /api/v1/jobs/:id: job status</li>
        </ul>
        <p className="mt-3">
          Send <span className="text-gray-300">Authorization: Bearer YOUR_API_KEY</span> on every
          request.{" "}
          <a
            href={API_DOCS_URL}
            target="_blank"
            rel="noopener noreferrer"
            className="text-accent hover:underline"
          >
            Full API docs
          </a>
        </p>
      </div>
    </div>
  );
}
