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

import { useDefaultProps } from '../../hooks';
import { useLocalization } from '../../localization';
import { MultiSelect, MultiSelectOption, MultiSelectProps } from '../multi-select';

export type RHFMultiSelectProps<
	TFieldValues extends FieldValues = FieldValues,
	TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
	TOptions extends readonly MultiSelectOption<any>[] = []
> = Omit<MultiSelectProps<TOptions>, 'value' | 'name' | 'disabled' | 'error'> & UseControllerProps<TFieldValues, TName>;

function RHFMultiSelect<
	TFieldValues extends FieldValues,
	TName extends FieldPath<TFieldValues>,
	TOptions extends readonly MultiSelectOption<any>[]
>(inProps: RHFMultiSelectProps<TFieldValues, TName, TOptions>) {
	const { translate } = useLocalization();

	const {
		/** React Hook Form */
		name,
		rules,
		control,
		disabled,
		defaultValue,
		shouldUnregister,
		/** React Hook Form */

		required,
		helperText,
		label,
		onChange,
		onBlur,
		...other
	} = useDefaultProps({ name: 'ReevolveRHFMultiSelect', props: inProps });

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

	const onChangeHandler: MultiSelectProps<TOptions>['onChange'] = (value, event, child) => {
		field.onChange(value);
		onChange?.(value, event, child);
	};

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

	return (
		<MultiSelect
			{...other}
			name={field.name}
			label={label}
			value={field.value}
			disabled={field.disabled}
			inputRef={field.ref}
			onChange={onChangeHandler}
			onBlur={onBlurHandler}
			error={!!error}
			helperText={error?.message ?? helperText}
			required={
				isBoolean(rules?.required) ? rules.required : isString(rules?.required) || rules?.required?.value || required
			}
		/>
	);
}

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

export default RHFMultiSelect;
