import { MenuItem, Stack, TextField, Typography } from "@mui/material";
import { useFormik } from "formik";
import { FC } from "react";
import { useTranslation } from "react-i18next";

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

import { useBuilderFactory } from "../hooks/useBuilderFactory";
import { useReportStore } from "../store/useReportsStore";

import { ReportBuilderContextProvider } from "./ReportBuilderContext";

export const ReportTypeSelector: FC = () => {
	const state = useReportStore();
	console.assert(
		state.assetIdList.length > 0,
		"state.assetIdList.length > 0",
	);
	// const objectList = useWatcherStore().assets.filter((x) =>
	// 	state.assetIdList.includes(x.id)
	// );
	const { t } = useTranslation();
	const { create: createBuilder } = useBuilderFactory();

	const selectTypeFormik = useFormik({
		initialValues: {
			type: state.reportType || ReportType.ByState,
		},
		onSubmit: (values) => {
			state.setReportType(values.type);
		},
	});

	// const getName = (id: string) => {
	// 	return objectList.find((x) => x.id === id)?.name || t("unknownObject");
	// };

	// const title =
	// 	state.assetIdList.length === 1
	// 		? t("reportByObject", { name: getName(state.assetIdList[0]) })
	// 		: t("reportByCountObject", { count: state.assetIdList.length });

	const typeList = [
		{
			value: ReportType.ByState,
			label: t("reportByObjectState"),
		},
		{
			value: ReportType.Journal,
			label: t("objectJournal"),
		},
		{
			value: ReportType.SummaryEvents,
			label: t("Summary report on events and alarms"),
		},
	];

	const builder = createBuilder(selectTypeFormik.values.type);

	return (
		<Stack spacing={3}>
			<form onSubmit={selectTypeFormik.handleSubmit}>
				<TextField
					label={t("reportType")}
					name="type"
					select
					fullWidth
					value={selectTypeFormik.values.type}
					onChange={(e) => {
						selectTypeFormik.handleChange(e);
						selectTypeFormik.submitForm();
					}}
					onBlur={selectTypeFormik.handleBlur}
					error={
						Boolean(selectTypeFormik.errors.type) &&
						selectTypeFormik.touched.type
					}
					helperText={
						selectTypeFormik.touched.type &&
						selectTypeFormik.errors.type
					}
					variant="outlined"
					className="mt-2"
					size="small"
				>
					{typeList.map((option) => (
						<MenuItem key={option.value} value={option.value}>
							{option.label}
						</MenuItem>
					))}
				</TextField>
			</form>

			<Stack spacing={1}>
				<Typography variant="body1">
					{t("Параметры отчёта:")}
				</Typography>
				<ReportBuilderContextProvider assetIdList={state.assetIdList}>
					{builder.renderExtraProperties()}
				</ReportBuilderContextProvider>
			</Stack>
		</Stack>
	);
};
