"use client";

import { useEffect, useState } from "react";

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

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

type ExtensionRequest = {
  id: string;
  status: string;
  message: string;
  requestedAt: string;
  processedAt: string | null;
  adminNote: string | null;
};

type ExtensionUsage = {
  used: number;
  limit: number;
  remaining: number;
  requests: ExtensionRequest[];
};

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

export function ApiKeySettings({
  initialStatus,
  initialRateLimit,
  initialExtensionUsage,
}: Props) {
  const [status, setStatus] = useState(initialStatus);
  const [rateLimit, setRateLimit] = useState(initialRateLimit);
  const [extensionUsage, setExtensionUsage] = useState(initialExtensionUsage);
  const [newKey, setNewKey] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [requesting, setRequesting] = 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);
    setNewKey(null);
    setSuccess(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? External integrations will stop working.")) return;

    setLoading(true);
    setError(null);
    setSuccess(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);
    }
  }

  async function requestRateLimitExtension() {
    if (extensionUsage.remaining <= 0) return;

    const reason = prompt(
      "Optional: tell us why you need a higher API rate limit (leave blank to skip).",
    );
    if (reason === null) return;

    setRequesting(true);
    setError(null);
    setSuccess(null);

    try {
      const res = await fetch("/api/account/api-rate-limit-extension-request", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message: reason }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to submit request");

      setExtensionUsage({
        used: data.used,
        limit: data.limit,
        remaining: data.remaining,
        requests: data.requests ?? extensionUsage.requests,
      });
      setSuccess(
        `Rate limit extension request submitted. ${data.used} of ${data.limit} used this year.`,
      );
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to submit request");
    } finally {
      setRequesting(false);
    }
  }

  const hasPending = extensionUsage.requests.some((r) => r.status === "PENDING");
  const usedPct = Math.min(100, Math.round((rateLimit.used / Math.max(1, rateLimit.limit)) * 100));

  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. Pro plan
        only.
      </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
          {rateLimit.bonus ? (
            <span className="text-gray-500"> (includes +{rateLimit.bonus} bonus)</span>
          ) : null}
        </p>
        <div className="h-2 overflow-hidden rounded bg-gray-800">
          <div
            className={`h-full rounded transition-all ${
              usedPct >= 90 ? "bg-red-500" : usedPct >= 70 ? "bg-amber-500" : "bg-accent"
            }`}
            style={{ width: `${usedPct}%` }}
          />
        </div>
        <p className="text-xs text-gray-500">
          {rateLimit.remaining} requests remaining · window {rateLimit.windowSeconds}s
        </p>

        <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
          <p className="text-xs text-gray-400">
            Extension requests this year: {extensionUsage.used} / {extensionUsage.limit}
          </p>
          <button
            type="button"
            onClick={requestRateLimitExtension}
            disabled={requesting || extensionUsage.remaining <= 0 || hasPending}
            className="inline-flex items-center justify-center rounded border border-accent/40 px-3 py-1.5 text-xs font-medium text-accent transition-colors hover:bg-accent/10 disabled:cursor-not-allowed disabled:opacity-50"
          >
            {requesting
              ? "Submitting…"
              : hasPending
                ? "Pending request"
                : extensionUsage.remaining <= 0
                  ? "No extensions left"
                  : "Request rate limit extension"}
          </button>
        </div>

        {extensionUsage.requests.length > 0 && (
          <ul className="space-y-1 border-t border-gray-800 pt-3 text-xs text-gray-500">
            {extensionUsage.requests.slice(0, 5).map((req) => (
              <li key={req.id}>
                {new Date(req.requestedAt).toLocaleDateString()} · {req.status}
                {req.adminNote ? ` · ${req.adminNote}` : ""}
              </li>
            ))}
          </ul>
        )}
      </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. For many audio files, upload each file then call{" "}
          <span className="text-gray-300">/api/v1/jobs</span> (avoid large one-shot batches).{" "}
          <a href="/dashboard/api-docs" className="text-accent hover:underline">
            Full API docs
          </a>
        </p>
      </div>
    </div>
  );
}
