import React from 'react';
import { TextFieldProps } from '@mui/material';
import { useDefaultProps } from '@mui/material/DefaultPropsProvider';
import { DatePicker as MuiDatePicker, DatePickerProps as MuiDatePickerProps } from '@mui/x-date-pickers';
import { isNil } from 'lodash';

import PickersLocalizationProvider, { PickersLocalizationProviderProps } from '../shared/PickersLocalizationProvider';

export type DatePickerProps<
	TLocale = any,
	TEnableAccessibleFieldDOMStructure extends boolean = true
> = MuiDatePickerProps<TEnableAccessibleFieldDOMStructure> &
	PickersLocalizationProviderProps<TLocale> & {
		required?: boolean;
		error?: boolean;
		helperText?: string;
		variant?: TextFieldProps['variant'];
		size?: TextFieldProps['size'];
		color?: TextFieldProps['color'];
		onBlur?: () => void;
	};

const DatePicker = <TLocale, TEnableAccessibleFieldDOMStructure extends boolean>(
	inProps: DatePickerProps<TLocale, TEnableAccessibleFieldDOMStructure>
) => {
	const {
		required,
		dateAdapter,
		helperText,
		adapterLocale,
		value,
		disabled,
		onOpen,
		onClose,
		open,
		onBlur,
		error,
		variant,
		size,
		color,
		...props
	} = useDefaultProps({ name: 'RemateDatePicker', props: inProps });

	const [openCalendar, setOpenCalendar] = React.useState(false);

	return (
		<PickersLocalizationProvider
			dateAdapter={dateAdapter}
			adapterLocale={adapterLocale}
		>
			<MuiDatePicker
				open={open ?? openCalendar}
				onOpen={() => {
					onOpen?.();

					if (isNil(open)) {
						setOpenCalendar(true);
					}
				}}
				onClose={() => {
					onClose?.();

					if (isNil(open)) {
						setOpenCalendar(false);
					}

					onBlur?.();
				}}
				{...props}
				slotProps={{
					...props.slotProps,
					textField: {
						onKeyDown(e) {
							e.preventDefault();
						},
						...(!disabled && {
							onClick: () => {
								onOpen?.();

								if (isNil(open)) {
									setOpenCalendar(true);
								}
							}
						}),
						required: required,
						helperText: helperText,
						variant: variant as any,
						size,
						color,
						fullWidth: true,
						error: error,
						...props.slotProps?.textField
					}
				}}
				value={value ?? null}
			/>
		</PickersLocalizationProvider>
	);
};

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

export default DatePicker;
