"use client";

import { useTransition, type ReactNode } from "react";

type Props = {
  action: () => Promise<void>;
  children: ReactNode;
  pendingChildren?: ReactNode;
  className?: string;
  pendingClassName?: string;
  disabled?: boolean;
  type?: "button" | "submit";
};

export function ActionButton({
  action,
  children,
  pendingChildren,
  className,
  pendingClassName,
  disabled = false,
  type = "button",
}: Props) {
  const [isPending, startTransition] = useTransition();

  const handleClick = (e: React.MouseEvent) => {
    if (isPending) return;
    e.stopPropagation();
    startTransition(async () => {
      await action();
    });
  };

  const classNames = [className, isPending && pendingClassName].filter(Boolean).join(" ");

  return (
    <button
      type={type}
      onClick={handleClick}
      disabled={disabled || isPending}
      className={classNames}
    >
      {isPending && pendingChildren ? pendingChildren : children}
    </button>
  );
}
