import { ForwardedRef, forwardRef, ReactNode } from 'react';
import {
	Checkbox as MuiCheckbox,
	CheckboxProps as MuiCheckboxProps,
	FormControl,
	FormControlLabel,
	FormControlLabelProps,
	FormControlProps,
	FormHelperText,
	FormHelperTextProps
} from '@mui/material';

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

export type CheckBoxProps = Omit<MuiCheckboxProps, 'value' | 'checked'> & {
	label?: string;
	required?: boolean;
	helperText?: ReactNode;
	value?: boolean;
	error?: boolean;
	disabled?: boolean;
	name?: string;
	slotProps?: {
		formControlLabel?: Omit<FormControlLabelProps, 'control' | 'ref' | 'label' | 'required'>;
		helperText?: FormHelperTextProps;
		formControl?: Omit<FormControlProps, 'name' | 'disabled' | 'error' | 'children' | 'defaultValue'>;
	};
};

const Checkbox = forwardRef(function Checkbox(inProps: CheckBoxProps, ref: ForwardedRef<unknown>) {
	const {
		label,
		required,
		helperText,
		onChange,
		onBlur,
		value,
		name,
		error,
		disabled,
		indeterminate,

		slotProps: {
			formControl: formControlProps,
			formControlLabel: formControlLabelProps,
			helperText: helperTextProps,
			...checkboxSlotProps
		} = {},
		...checkboxProps
	} = useDefaultProps({ name: 'RemateCheckbox', props: inProps });

	return (
		<FormControl
			{...formControlProps}
			error={error}
			disabled={disabled}
		>
			<FormControlLabel
				{...formControlLabelProps}
				name={name}
				control={
					<MuiCheckbox
						{...checkboxProps}
						slotProps={checkboxSlotProps}
						indeterminate={indeterminate}
						value={value}
						checked={value}
						onBlur={onBlur}
						onChange={onChange}
					/>
				}
				ref={ref}
				label={label}
				required={required}
			/>

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

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

export default Checkbox;
