import React, { useContext } from 'react';
import { Button } from '@cloudflare/component-button';
import FormContext from './FormContext';
import { Trans } from '@cloudflare/intl-react';

type Props = Omit<React.ComponentProps<typeof Button>, 'name'> & {
  name?: string;
  children?: React.ReactNode;
  className?: string;
};

export default function Submit({
  name,
  type = 'primary',
  className,
  children,
  ...rest
}: Props) {
  const context = useContext(FormContext);
  const handleClick = () => {
    if (name) {
      context.setSubmitButtonName(name);
    }

    // Force form submission when name is used as this implies multiple submit
    // buttons are used
    if (name) {
      context.formRef.current?.dispatchEvent(new Event('submit'));
    }
  };
  return (
    <Button
      type={type}
      onClick={handleClick}
      loading={context.isSubmitting}
      className={className}
      {...rest}
      // In the case of multiple submit buttons (where names are set),
      // standard buttons are used, to make sure there's no default action
      // for accessibility reasons.
      submit={!name}
    >
      {children || <Trans id="common.submit" />}
    </Button>
  );
}
