import React, {
  FC,
  MouseEvent,
  ReactNode,
  useRef
} from 'react'

import Button from '../button'
import Loading from '../loading'

type FormProps = {
  children: ReactNode,
  className?: string,
  loading: boolean,
  submitCallback: (e: MouseEvent) => void,
  submitted: boolean,
  valid: boolean,
  [other:string]: unknown
}

const Form:FC<FormProps> = ({
  children,
  className,
  loading,
  submitCallback,
  submitted,
  valid,
  ...other
}: FormProps) => {
  const ref = useRef<HTMLFormElement>(null)
  
  return (
    <form className={className} ref={ref} {...other}>
      {children}
      {loading &&
        <Loading
          button={false}
          className="mt-3 ml-auto"
          variant="indigo"
        />
      }
      {valid && !submitted && !loading &&
        <Button
          className="mt-3 ml-auto"
          onClick={(e: MouseEvent) => submitCallback(e)}
          variant="outline-indigo"
        >
          Submit
        </Button>
      }
      {!valid && !submitted && !loading &&
        <Button
          className="mt-3 ml-auto"
          variant="outline-indigo"
          disabled
        >
          Submit
        </Button>
      }
    </form>
  )
}

export default Form
