import * as React from 'react'
import {useForm} from 'react-hook-form'
import Method from './Method'

type Props = {
	method: Method,
	action: string,
	href?: string,
	headers?: Record<string, string>,
	onResponse?: (...args: unknown[]) => unknown,
	onError?: (...args: unknown[]) => unknown,
	onSubmit?: (...args: unknown[]) => unknown,
	children: (...args: unknown[]) => unknown,
}

const Form: React.FC<Props> = ({
	method,
	action,
	href,
	children,
	onResponse,
	onError,
	headers,
	onSubmit,
}) => {
	const onFormSubmit = async (body) => {
		const response = await fetch(href, {
			method,
			body,
			headers,
		})
		const data = await response.json()
		if (typeof (onResponse as unknown) === 'function') {
			onResponse(data)
		}
	}

	const {register, handleSubmit} = useForm()

	return (
		<form
			method={method === Method.GET ? 'get' : 'post'}
			action={action}
			onSubmit={handleSubmit(onSubmit || onFormSubmit, onError)}
		>
			{children({ register })}
		</form>
	)
}

export default Form
