"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { useConfirm } from "@/components/shared/use-confirm";

export function BanRingButton({ userIds, label }: { userIds: number[]; label: string }) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const { confirm: askConfirm, dialog: confirmDialog } = useConfirm();

  async function handleBanAll() {
    if (
      !(await askConfirm(
        {
          title: "Ban fraud ring",
          message: `Are you sure you want to ban ${userIds.length} accounts? This action will mark all accounts in this ring as banned.`
        }
      ))
    )
      return;

    setLoading(true);
    try {
      const res = await fetch("/api/admin/fraud/ban-ring", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ userIds, reason: `Fraud ring detection: ${label}` }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        alert(data.error || "Failed to ban accounts");
      } else {
        router.refresh();
      }
    } catch {
      alert("Failed to ban accounts");
    } finally {
      setLoading(false);
    }
  }

  return (
    <>
      {confirmDialog}
      <button
        disabled={loading}
        onClick={handleBanAll}
        className="bg-red-600 hover:bg-red-700 text-white px-3 py-1.5 rounded-lg transition-colors text-xs font-medium disabled:opacity-50 shrink-0"
      >
        {loading ? "Banning..." : `Ban All (${userIds.length})`}
      </button>
    </>
  );
}
