"use client";

import { useState } from "react";
import { Button, Field, Input } from "@/components/ui/form";

export default function AdminBetaInvitesPage() {
  const [dryRun, setDryRun] = useState(true);
  const [limit, setLimit] = useState("1");
  const [tokenMinutes, setTokenMinutes] = useState("30");
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<any>(null);
  const [error, setError] = useState<string | null>(null);

  async function runInvites() {
    setLoading(true);
    setError(null);
    setResult(null);

    try {
      const qs = new URLSearchParams({
        dryRun: String(dryRun),
        limit: String(limit || "0"),
        tokenMinutes: String(tokenMinutes || "30"),
      });

      const res = await fetch(`/api/admin/beta-invites?${qs.toString()}`, {
        method: "POST",
      });

      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data?.message || data?.error || "Request failed");

      setResult(data);
    } catch (e: any) {
      setError(e?.message ?? "Failed");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-xl font-semibold">Send Beta Invites</h1>
        <p className="mt-1 text-sm text-zinc-400">
          Runs the backend batch invite sender (uses your email templates + tracking).
        </p>
      </div>

      <div className="rounded-lg border border-zinc-900 bg-zinc-950 p-4 space-y-4">
        <label className="flex items-center gap-2 text-sm text-zinc-200">
          <input
            type="checkbox"
            checked={dryRun}
            onChange={(e) => setDryRun(e.target.checked)}
          />
          Dry run (do everything except actually send)
        </label>

        <div className="grid gap-4 md:grid-cols-3">
          <Field label="Limit" htmlFor="limit">
            <Input id="limit" value={limit} onChange={(e) => setLimit(e.target.value)} />
          </Field>

          <Field label="Token minutes" htmlFor="tokenMinutes">
            <Input
              id="tokenMinutes"
              value={tokenMinutes}
              onChange={(e) => setTokenMinutes(e.target.value)}
            />
          </Field>
        </div>

        <Button onClick={runInvites} disabled={loading}>
          {loading ? "Running…" : "Send Beta Invites"}
        </Button>

        {error && (
          <div className="rounded-md border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-200">
            {error}
          </div>
        )}

        {result && (
          <pre className="overflow-auto rounded-md border border-zinc-800 bg-black/40 p-3 text-xs text-zinc-200">
            {JSON.stringify(result, null, 2)}
          </pre>
        )}
      </div>
    </div>
  );
}