import { Checkbox, FormControlLabel, Typography } from "@mui/material";
import { Stack } from "@mui/system";
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 {
	OnlyUserLogs: boolean;
	OnlyFire: boolean;
	From: Date;
	To: Date;
}

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

export function JournalReportProperties({ onIsValid }: ReportExtraProps) {
	const { t } = useTranslation();
	const { type, getExtraForType, setExtraForType } = useReportBuilderStore();

	const initialValues: FormType = {
		OnlyUserLogs: false,
		OnlyFire: false,
		From: dayjs().startOf("day").toDate(),
		To: dayjs().toDate(),
	};

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

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

	const handlePropertyChange = (
		event: React.ChangeEvent<HTMLInputElement>,
	) => {
		formik.setFieldValue(event.target.name, event.target.checked);
	};

	return (
		<form onSubmit={formik.handleSubmit}>
			<Stack spacing={3}>
				<Stack spacing={1}>
					<FormControlLabel
						control={
							<Checkbox
								checked={formik.values.OnlyUserLogs}
								onChange={handlePropertyChange}
								name="OnlyUserLogs"
							/>
						}
						label={
							<Typography variant="subtitle1">
								{t("Only user logs")}
							</Typography>
						}
						sx={{
							userSelect: "none",
						}}
					/>
					<FormControlLabel
						control={
							<Checkbox
								checked={formik.values.OnlyFire}
								onChange={handlePropertyChange}
								name="OnlyFire"
							/>
						}
						label={
							<Typography variant="subtitle1">
								{t("Only fire events")}
							</Typography>
						}
						sx={{
							userSelect: "none",
						}}
					/>
					<DateTimeRangePicker
						name="dateRange"
						onChange={(_, x) => {
							formik.setFieldValue("From", x.from);
							formik.setFieldValue("To", x.to);
						}}
					/>
				</Stack>
			</Stack>
		</form>
	);
}
