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, label } from "../../model";

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

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