'use client';
import { Button } from '@/components/ui';
import { type ComponentProps } from 'react';
import { useFormStatus } from 'react-dom';
import { Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';

export type SubmitButtonProps = Omit<
  ComponentProps<typeof Button>,
  'type' | 'aria-disabled'
> & {
  pendingText?: string;
  pendingTextProps?: ComponentProps<'p'>;
  loaderProps?: ComponentProps<typeof Loader2>;
};

export const SubmitButton = ({
  children,
  className,
  pendingText = 'Submitting...',
  pendingTextProps,
  loaderProps,
  ...props
}: SubmitButtonProps) => {
  const { pending } = useFormStatus();
  return (
    <Button
      type='submit'
      aria-disabled={pending}
      {...props}
      className={cn('cursor-pointer', className)}
    >
      {pending || props.disabled ? (
        <>
          <Loader2
            {...loaderProps}
            className={cn('mr-2 h-4 w-4 animate-spin', loaderProps?.className)}
          />
          <p {...pendingTextProps}
            className={cn('text-sm font-medium', pendingTextProps?.className)}
          >
            {pendingText}
          </p>
        </>
      ) : (
        children
      )}
    </Button>
  );
};
