'use client';

import { useEffect, useState } from 'react';
import { useFormStatus } from 'react-dom';
import { Spinner } from './Icons';

type BtnProps = Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'type'> & {
  /** Shown while the server action runs */
  pendingLabel?: string;
  /** Ask before running — for merges, rejections and anything hard to undo */
  confirm?: string;
};

/**
 * Submit button for server-action forms: every button in the form is disabled while the action
 * runs (no double submits), the pressed one shows a spinner, and it can ask for confirmation first.
 */
export function SubmitButton({ children, pendingLabel, confirm: question, className = 'btn btn-primary btn-sm', onClick, disabled, ...rest }: BtnProps) {
  const { pending } = useFormStatus();
  const [pressed, setPressed] = useState(false);
  useEffect(() => {
    if (!pending) setPressed(false);
  }, [pending]);
  const busy = pending && pressed;
  return (
    <button
      type="submit"
      {...rest}
      disabled={disabled || pending}
      aria-busy={busy || undefined}
      onClick={(e) => {
        if (question && !window.confirm(question)) {
          e.preventDefault();
          return;
        }
        setPressed(true);
        onClick?.(e);
      }}
      className={className}
    >
      {busy && <Spinner className="h-3.5 w-3.5" />}
      {busy && pendingLabel ? pendingLabel : children}
    </button>
  );
}
