"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";

export function ResetUsageButton({ userId }: { userId: string }) {
  const router = useRouter();
  const [resetting, setResetting] = useState(false);

  async function handleReset() {
    if (!confirm("Reset this user's AI call count for the current month?")) return;
    setResetting(true);
    try {
      const res = await fetch(`/api/v1/admin/users/${userId}/usage`, { method: "PATCH" });
      if (!res.ok) throw new Error("Reset failed");
      toast.success("AI call count reset");
      router.refresh();
    } catch {
      toast.error("Failed to reset usage");
    } finally {
      setResetting(false);
    }
  }

  return (
    <Button
      variant="outline"
      size="sm"
      onClick={() => { void handleReset(); }}
      disabled={resetting}
      className="text-destructive hover:text-destructive"
    >
      {resetting ? "Resetting…" : "Reset AI Calls"}
    </Button>
  );
}
