"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { buttonClass } from "@/components/ui";

// Admin marks an organizer verified after contacting them (or undoes it).
export default function VerifyButton({
  organizerId,
  verified,
  size = "sm",
}: {
  organizerId: string;
  verified: boolean;
  size?: "sm" | "md";
}) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function toggle() {
    setLoading(true);
    setError(null);
    const res = await fetch("/api/admin/organizers/verify", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ organizerId, verified: !verified }),
    });
    const data = await res.json().catch(() => ({}));
    setLoading(false);
    if (!res.ok) {
      setError(data.error || "Failed");
      return;
    }
    router.refresh();
  }

  return (
    <span className="inline-flex flex-col items-start gap-1">
      <button
        type="button"
        onClick={toggle}
        disabled={loading}
        className={buttonClass(verified ? "ghost" : "primary", `whitespace-nowrap ${size === "sm" ? "px-2.5 py-1 text-xs" : ""}`)}
      >
        {loading ? "Saving…" : verified ? "Undo verification" : "Mark verified"}
      </button>
      {error && <span className="text-xs text-red-500">{error}</span>}
    </span>
  );
}
