import { Checkbox, FormControlLabel, Typography } from "@mui/material";
import { Stack } from "@mui/system";
import dayjs from "dayjs";
import { FC } from "react";
import { useTranslation } from "react-i18next";
import { z } from "zod";

import { ReportType } from "@/contracts/client.schemas";

import { DateRange } from "../components/DateRange";
import { ReportBuilderActions } from "../components/ReportBuilderActions";
import { useReportForm } from "../hooks/useReportForm";

interface FormType {
	OnlyUserLogs: boolean;
	OnlyFire: boolean;
	From: string;
	To: string;
}

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

export const JournalProperties: FC = () => {
	const { t } = useTranslation();

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

	const formik = useReportForm(
		initialValues,
		validationSchema,
		ReportType.Journal,
	);

	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",
						}}
					/>
					<DateRange
						name="dateRange"
						onChange={(_, x) => {
							formik.setFieldValue("From", x[0]);
							formik.setFieldValue("To", x[1]);
						}}
					/>
				</Stack>

				<ReportBuilderActions
					isLoading={formik.isSubmitting}
					isValid={formik.isValid}
					onCancel={formik.resetForm}
				/>
			</Stack>
		</form>
	);
};
