import React from 'react';
import { TextFieldProps } from '@mui/material';
import { useDefaultProps } from '@mui/material/DefaultPropsProvider';
import { TimePicker as MuiTimePicker, TimePickerProps as MuiTimePickerProps } from '@mui/x-date-pickers';
import { isNil } from 'lodash';

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

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

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

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

	return (
		<PickersLocalizationProvider
			dateAdapter={dateAdapter}
			adapterLocale={adapterLocale}
		>
			<MuiTimePicker
				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,
						error: error,
						fullWidth: true,
						variant: variant as any,
						size,
						color,
						...props.slotProps?.textField
					}
				}}
				value={value ?? null}
			/>
		</PickersLocalizationProvider>
	);
};

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

export default TimePicker;
