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

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

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

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

		label,
		required,
		helperText,
		onChange,
		onBlur,

		...props
	} = useDefaultProps({ name: 'RemateRHFTimePicker', 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 (
		<TimePicker
			{...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 {
		RemateRHFTimePicker?: {
			defaultProps?: Partial<RHFTimePickerProps>;
		};
	}
}

export default RHFTimePicker;
