/* eslint-disable @typescript-eslint/no-explicit-any */
import { FormikValues } from "formik";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";

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

import { useReportBuilderContext } from "../components/useReportBuilderContext";
import { useReportStore } from "../store/useReportsStore";

import { reportApi } from "./useReportApi";

export function useReportForm<T extends FormikValues>(
	initialValues: T,
	validationSchema: any,
	reportType: ReportType,
) {
	const context = useReportBuilderContext();
	const navigate = useNavigate();
	const setCurrentReportId = useReportStore((x) => x.setCurrentReportId);
	const formik = useFormikWithZod({
		initialValues: initialValues,
		validationSchema: validationSchema,
		validateOnBlur: true,
		validateOnChange: true,
		validateOnMount: true,

		onSubmit: async (values) => {
			try {
				const response = await reportApi.create({
					assetIdList: context.assetIdList,
					type: reportType,
					extra: JSON.stringify(values),
				});

				context.closeDialog();
				setCurrentReportId(response.id);

				navigate("../reports", {
					relative: "path",
				});
			} catch (e) {
				toast.error((e as Error).message);
			}
		},
	});

	return formik;
}
