import { Ref } from 'react';
import {
	FormControl,
	FormControlProps,
	FormHelperText,
	FormHelperTextProps,
	FormLabel,
	FormLabelProps,
	TextFieldProps,
	useTheme
} from '@mui/material';
import { isFunction } from 'lodash';
import { MuiOtpInput, MuiOtpInputProps } from 'mui-one-time-password-input';

import { useDefaultProps } from '../../hooks';

export type CodeFieldProps = MuiOtpInputProps & {
	label?: string;
	required?: boolean;
	helperText?: string;
	error?: boolean;
	disabled?: boolean;
	variant?: TextFieldProps['variant'];
	size?: TextFieldProps['size'];
	color?: TextFieldProps['color'];
	firstInputRef?: Ref<any>;

	slotProps?: {
		formLabel?: Omit<FormLabelProps, 'control' | 'ref' | 'label' | 'required'>;
		helperText?: FormHelperTextProps;
		formControl?: Omit<FormControlProps, 'name' | 'disabled' | 'error' | 'children' | 'defaultValue'>;
	};
};

export default function CodeField(inProps: CodeFieldProps) {
	const { direction } = useTheme();
	const {
		helperText,
		label,
		required,
		slotProps,
		disabled,
		error,
		value,
		TextFieldsProps,
		firstInputRef,
		size,
		variant,
		color,
		...props
	} = useDefaultProps({
		name: 'RemateCodeField',
		props: inProps
	});

	return (
		<FormControl
			fullWidth
			{...slotProps?.formControl}
			error={error}
			disabled={disabled}
			required={required}
		>
			{label && (
				<FormLabel
					sx={(theme) => ({
						pb: 0.75,
						...(isFunction(slotProps?.formLabel?.sx)
							? (slotProps.formLabel.sx as Function)(theme)
							: slotProps?.formLabel?.sx)
					})}
					{...slotProps?.formLabel}
				>
					{label}
				</FormLabel>
			)}

			<MuiOtpInput
				{...(direction === 'rtl' && {
					dir: 'ltr',
					justifyContent: 'end'
				})}
				{...props}
				value={value ?? ''}
				TextFieldsProps={(index) => ({
					disabled,
					error,
					size,
					variant,
					color,
					...(index === 0 && { inputRef: firstInputRef }),
					...(isFunction(TextFieldsProps) ? TextFieldsProps(index) : TextFieldsProps)
				})}
			/>

			{helperText && <FormHelperText {...slotProps?.helperText}>{helperText}</FormHelperText>}
		</FormControl>
	);
}

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