'use client';

import type { ComponentProps } from 'react';
import { Loader2 } from 'lucide-react';
import { useFormStatus } from 'react-dom';

import { Button, cn } from '@gib/ui';

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>
  );
};
