import { AdapterMoment } from "@mui/x-date-pickers/AdapterMoment";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { Moment } from "moment/moment";
import { FC } from "react";

import { INVALID_DATE } from "shared/model/consts";
import { EDateFormat } from "shared/model/enums";
import { WithDatePickerStyles } from "shared/ui/styles";

import { applyFilter, datePickerProps } from "../../lib";
import { IProps, defaultValue } from "../../model";

export const DateInput: FC<IProps> = ({ label, setValue, value }) => {
	function onChange(date: Moment | null) {
		const dayString = date?.format(EDateFormat.db) || "";
		const newValue = {
			...value,
			1: dayString === INVALID_DATE ? defaultValue[1] : dayString,
		};
		setValue(newValue);
		applyFilter(newValue);
	}

	return (
		<LocalizationProvider dateAdapter={AdapterMoment}>
			<WithDatePickerStyles>
				<DatePicker
					label={label}
					onChange={onChange}
					{...datePickerProps(value[1])}
				/>
			</WithDatePickerStyles>
		</LocalizationProvider>
	);
};
