import { Stack } from "@mui/material";
import dayjs from "dayjs";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { z } from "zod";

import { DateTimeRangePicker } from "@/shared/DateTimeRangePicker";
import { useReportBuilderStore } from "@/store/report-builder.store";
import { useFormikWithZod } from "@/utils/useFormikWithZod";

import { ReportExtraProps } from "../model/ReportExtraProps";

interface FormType {
	From: Date;
	To: Date;
}

export function SummaryEventsExtraProperties({ onIsValid }: ReportExtraProps) {
	const { t } = useTranslation("translation");
	const { type, getExtraForType, setExtraForType } = useReportBuilderStore();
	const initialValues: FormType = {
		From: dayjs().startOf("day").toDate(),
		To: dayjs().toDate(),
	};

	const validationSchema = z.object({
		From: z.date(),
		To: z.date(),
	});

	const formik = useFormikWithZod({
		initialValues: (getExtraForType(type) as FormType) || initialValues,
		validationSchema,
		onSubmit: () => {},
	});

	useEffect(() => {
		setExtraForType(type, formik.values);
	}, [formik.values, type, setExtraForType]);

	useEffect(() => {
		onIsValid(formik.isValid);
	}, [formik.isValid]);

	return (
		<form onSubmit={formik.handleSubmit}>
			<Stack spacing={3}>
				<DateTimeRangePicker
					name="dateRange"
					onChange={(_, x) => {
						formik.setFieldValue("From", x.from);
						formik.setFieldValue("To", x.to);
					}}
				/>
			</Stack>
		</form>
	);
}
