import { DetailedHTMLProps, FormHTMLAttributes } from 'react';
import { FieldValues, FormProvider, UseFormHandleSubmit, UseFormReturn } from 'react-hook-form';

import { useDefaultProps } from '../../hooks';

export type RHFFormProviderProps<
	TFieldValues extends FieldValues = FieldValues,
	TContext = any,
	TTransformedValues extends FieldValues | undefined = FieldValues | undefined
> = React.PropsWithChildren<{
	onSubmit: ReturnType<UseFormHandleSubmit<TFieldValues, TTransformedValues>>;
	methods: UseFormReturn<TFieldValues, TContext, TTransformedValues>;
	formElementProps?: Omit<
		DetailedHTMLProps<FormHTMLAttributes<HTMLFormElement>, HTMLFormElement>,
		'onSubmit' | 'noValidate'
	>;
}>;

function RHFForm<TFieldValues extends FieldValues, TContext, TTransformedValues extends FieldValues | undefined>(
	inProps: RHFFormProviderProps<TFieldValues, TContext, TTransformedValues>
) {
	const { children, onSubmit, methods, formElementProps } = useDefaultProps({ name: 'RemateRHFForm', props: inProps });

	return (
		<form
			autoComplete="off"
			{...formElementProps}
			onSubmit={onSubmit}
			noValidate
		>
			<FormProvider {...methods}>{children}</FormProvider>
		</form>
	);
}

declare module '@mui/material' {
	interface Components {
		RemateRHFForm?: {
			defaultProps?: Partial<RHFFormProviderProps>;
		};
	}
}

export default RHFForm;
