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

import { useDefaultProps } from '../../hooks';
import { useLocalization } from '../../localization';
import { Password, PasswordProps } from '../password';

export type RHFPasswordProps<T extends FieldValues = FieldValues, Nullable extends boolean = true> = Omit<
	PasswordProps<Nullable>,
	'value' | 'name' | 'disabled' | 'error'
> &
	UseControllerProps<T>;

function RHFPassword<T extends FieldValues, Nullable extends boolean>(inProps: RHFPasswordProps<T, Nullable>) {
	const {
		/** React Hook Form */
		name,
		rules,
		control,
		disabled,
		defaultValue,
		shouldUnregister,
		/** React Hook Form */
		required,
		helperText,
		label,
		onChange,
		onBlur,
		inputRef,
		...props
	} = useDefaultProps({ name: 'RemateRHFPassword', props: inProps });

	const { translate } = useLocalization();

	const {
		field,
		fieldState: { error }
	} = useController<T>({
		name,
		control,
		defaultValue,
		shouldUnregister,
		disabled,
		rules: rules && {
			...rules,
			required: rules?.required === true ? translate('validation.required', { label }) : rules?.required,
			pattern: isRegExp(rules?.pattern)
				? {
						value: rules.pattern,
						message: translate('validation.pattern', { label, pattern: rules.pattern })
					}
				: rules?.pattern,
			minLength: isNumber(rules?.minLength)
				? {
						value: rules.minLength,
						message: translate('validation.minLength', { minLength: rules.minLength, label })
					}
				: rules?.minLength,
			maxLength: isNumber(rules?.maxLength)
				? {
						value: rules.maxLength,
						message: translate('validation.maxLength', { maxLength: rules.maxLength, label })
					}
				: rules?.maxLength
		}
	});

	const isFieldRequired = isBoolean(rules?.required)
		? rules.required
		: isString(rules?.required) || rules?.required?.value || required;

	const onChangeHandler = (value: any, event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
		field.onChange(value);
		onChange?.(value, event);
	};

	const onBlurHandler = (e: React.FocusEvent<HTMLInputElement>) => {
		field.onBlur();
		onBlur?.(e);
	};

	return (
		<Password
			fullWidth
			{...props}
			label={label}
			inputRef={inputRef ?? field.ref}
			name={field.name}
			disabled={field.disabled}
			value={field.value}
			onChange={onChangeHandler}
			onBlur={onBlurHandler}
			required={isFieldRequired}
			error={!!error}
			helperText={error?.message ?? helperText}
		/>
	);
}

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

export default RHFPassword;
