"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { RefreshCw, type LucideIcon } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";

type Result = { ok: boolean; error?: string; data?: { summary?: string } } | void;

/**
 * Fire-and-toast button for the long-running maintenance actions of this page
 * ("Sync prices now", "Fetch from provider"). The server action returns a
 * one-line summary that lands in the toast.
 */
export function RunActionButton({
  action,
  label,
  pendingLabel,
  successTitle,
  values,
  icon: Icon = RefreshCw,
  variant = "outline",
}: {
  action: (formData: FormData) => Promise<Result>;
  label: string;
  pendingLabel: string;
  successTitle: string;
  values?: Record<string, string>;
  icon?: LucideIcon;
  variant?: "default" | "outline" | "secondary" | "ghost";
}) {
  const router = useRouter();
  const [pending, setPending] = React.useState(false);

  async function run() {
    if (pending) return;
    setPending(true);
    try {
      const formData = new FormData();
      for (const [key, value] of Object.entries(values ?? {})) formData.set(key, value);
      const result = await action(formData);
      if (result && result.ok === false) {
        toast.error(result.error || "Action failed");
      } else {
        const summary = result && result.ok ? result.data?.summary : undefined;
        toast.success(successTitle, summary ? { description: summary } : undefined);
        router.refresh();
      }
    } catch (e) {
      if (e && typeof e === "object" && "digest" in e) throw e;
      toast.error(e instanceof Error ? e.message : "Action failed");
    } finally {
      setPending(false);
    }
  }

  return (
    <Button type="button" size="sm" variant={variant} disabled={pending} onClick={run}>
      <Icon className={pending ? "size-3.5 animate-spin" : "size-3.5"} />
      {pending ? pendingLabel : label}
    </Button>
  );
}

export default RunActionButton;
