import { BoxProps, FormControl } from '@chakra-ui/react'
import { yupResolver } from '@hookform/resolvers/yup'
import React from 'react'
import { Mode, SubmitHandler, useForm } from 'react-hook-form'
import { AnyObjectSchema } from 'yup'

interface ICustomFormProps {
  defaultValues?: any
  children: JSX.Element[]
  onSubmit: SubmitHandler<any>
  validationSchema?: AnyObjectSchema
  mode?: Mode
}

const CustomForm: React.FunctionComponent<ICustomFormProps & BoxProps> = (props) => {
  const { defaultValues, children, onSubmit, validationSchema, mode = 'all', ...style } = props
  const {
    handleSubmit,
    register,
    formState: { errors },
  } = useForm({ defaultValues, mode, resolver: yupResolver(validationSchema) })

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <FormControl {...style}>
        {Array.isArray(children)
          ? children.map((child: any) => {
              return child.props.name
                ? React.createElement(child.type, {
                    ...{
                      ...child.props,
                      register,
                      errors,
                      key: child.props.name,
                    },
                  })
                : child
            })
          : children}
      </FormControl>
    </form>
  )
}

export default CustomForm
