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

import { useDefaultProps } from '../../hooks';
import { useLocalization } from '../../localization';
import { CodeField, CodeFieldProps } from '../code-field';

export type RHFCodeFieldProps<
	TFieldValues extends FieldValues = FieldValues,
	TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
	Nullable extends boolean = true
> = Omit<CodeFieldProps, 'error' | 'value' | 'onChange'> &
	UseControllerProps<TFieldValues, TName> & {
		/**
		 * When enabled, an empty string input ("") will be treated as a null value for the field
		 * @default true
		 */
		nullable?: Nullable;
		onChange?: (value: Nullable extends true ? string | null : string) => void;
	};

function RHFCodeField<TFieldValues extends FieldValues, TName extends FieldPath<TFieldValues>>(
	inProps: RHFCodeFieldProps<FieldValues, TName>
) {
	const {
		/** React Hook Form */
		name,
		control,
		defaultValue,
		disabled,
		shouldUnregister,
		rules,
		/** React Hook Form */

		label,
		required,
		onChange,
		onBlur,
		helperText,
		nullable = true,
		...props
	} = useDefaultProps({ name: 'RemateRHFCodeField', props: inProps });

	const { translate } = useLocalization();

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

	const {
		field,
		fieldState: { error }
	} = useController<FieldValues, TName>({
		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
		}
	});

	function onChangeHandler(value: string | null) {
		if (value === '' && nullable) {
			value = null;
		}

		field.onChange(value);
		onChange?.(value);
	}

	function onBlurHandler(value: string, isCompleted: boolean) {
		field.onBlur();

		onBlur?.(value, isCompleted);
	}

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

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

export default RHFCodeField;
