import { FieldValues, useController, UseControllerProps } from 'react-hook-form';
import { isBoolean, isString, isUndefined } from 'lodash';

import { useDefaultProps } from '../../hooks';
import { useLocalization } from '../../localization';
import { DatePicker, DatePickerProps } from '../date-pickers';

export type RHFDatePickerProps<
	T extends FieldValues = FieldValues,
	TLocale = any,
	TEnableAccessibleFieldDOMStructure extends boolean = true
> = Omit<DatePickerProps<TLocale, TEnableAccessibleFieldDOMStructure>, 'name' | 'disabled'> & UseControllerProps<T>;

const RHFDatePicker = <T extends FieldValues, TLocale, TEnableAccessibleFieldDOMStructure extends boolean>(
	inProps: RHFDatePickerProps<T, TLocale, TEnableAccessibleFieldDOMStructure>
) => {
	const {
		/** React Hook Form */
		name,
		rules,
		control,
		disabled,
		defaultValue,
		shouldUnregister,
		/** React Hook Form */

		label,
		required,
		helperText,
		onChange,
		onBlur,

		...props
	} = useDefaultProps({ name: 'RemateRHFDatePicker', props: inProps });

	const { translate } = useLocalization();

	const {
		field,
		fieldState: { error }
	} = useController({
		name,
		defaultValue,
		disabled,
		shouldUnregister,
		control,
		rules: rules && {
			...rules,
			required: rules?.required === true ? translate('validation.required', { label }) : rules?.required
		}
	});

	return (
		<DatePicker
			{...props}
			onBlur={() => {
				field.onBlur();
				onBlur?.();
			}}
			helperText={error?.message || helperText}
			required={
				isBoolean(rules?.required) ? rules.required : isString(rules?.required) || rules?.required?.value || required
			}
			label={label}
			error={!!error}
			value={isUndefined(field.value) ? null : field.value}
			inputRef={field.ref}
			disabled={field.disabled}
			name={field.name}
			onChange={(newValue, context) => {
				field.onChange(newValue);

				onChange?.(newValue, context);
			}}
		/>
	);
};

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

export default RHFDatePicker;
