import {
	RadioGroup,
	FormControlLabel,
	Radio,
	FormControl,
	FormLabel,
} from "@mui/material";
import { z } from "zod";

import { Loader } from "@/common/components/Loader";
import { useGetAssetGroupList } from "@/contracts/assets-groups";
import { useCreateDemoEvent } from "@/contracts/events";
import { DialogContent, DialogHeader, DialogTitle } from "@/shared";
import { Button } from "@/shared/Button";
import { useFormikWithZod } from "@/utils/useFormikWithZod";
import { useEffect, useState } from "react";
import { getAssetList, useGetAssetList } from "@/contracts/assets";
import { AssetModel } from "@/contracts/client.schemas";

export const SELECT_ASSET_GROUP_DIALOG_KEY = "select-asset-group-dialog";

type Props = {
	organizationId: string;
};

type FormValues = {
	assetGroupId: string;
	assetId: string;
};

const defaultValue: FormValues = {
	assetGroupId: "",
	assetId: "",
};

export const SelectAssetGroupDialog = ({ organizationId }: Props) => {
	const { data: groups, isLoading: groupsLoading } = useGetAssetGroupList({
		OrganizationId: organizationId,
	});
	const [viewAssets, setViewAssets] = useState<AssetModel[]>([]);

	const generateDemoEvent = useCreateDemoEvent();
	const formik = useFormikWithZod({
		initialValues: defaultValue,
		validationSchema: z.object({
			assetGroupId: z.string().min(1, "Обязательное поле"),
			assetId: z.string().min(1, "Обязательное поле"),
		}),
		onSubmit: async (values) => {
			await generateDemoEvent.mutateAsync({
				data: values,
			});
		},
	});

	useEffect(() => {
		async function getAssets() {
			const table = await getAssetList({
				OrganizationId: organizationId,
				GroupId: formik.values.assetGroupId,
			});
			setViewAssets(table?.items ?? []);
		}

		if (formik.values.assetGroupId) {
			getAssets();
		}
	}, [formik.values.assetGroupId]);

	return (
		<DialogContent size="lg">
			<DialogHeader>
				<DialogTitle>
					Выбор группы объектов для генерации демо-событий
				</DialogTitle>
			</DialogHeader>

			{groupsLoading && (
				<div className="flex h-full items-center justify-center">
					<Loader />
				</div>
			)}

			{!groupsLoading && groups && (
				<div className="flex h-full items-center justify-center text-sm">
					<form onSubmit={formik.handleSubmit}>
						<div className="flex items-start gap-4">
							<FormControl component="fieldset">
								<FormLabel component="legend">
									Выберите группу объектов
								</FormLabel>
								<RadioGroup
									name="assetGroupId"
									value={formik.values["assetGroupId"] ?? ""}
									onChange={formik.handleChange}
									onBlur={formik.handleBlur}
								>
									{groups &&
										groups.items.map((option) => (
											<FormControlLabel
												key={option.id}
												value={option.id}
												control={<Radio />}
												label={option.name}
											/>
										))}
								</RadioGroup>
								{formik.touched["assetGroupId"] &&
									formik.errors["assetGroupId"] && (
										<div className="text-sm text-red-500">
											{formik.errors["assetGroupId"]}
										</div>
									)}
							</FormControl>

							{viewAssets.length > 0 && (
								<FormControl component="fieldset">
									<FormLabel component="legend">
										Выберите объект
									</FormLabel>
									<RadioGroup
										name="assetId"
										value={formik.values["assetId"] ?? ""}
										onChange={formik.handleChange}
										onBlur={formik.handleBlur}
									>
										{viewAssets.map((option) => (
											<FormControlLabel
												key={option.id}
												value={option.id}
												control={<Radio />}
												label={option.name}
											/>
										))}
									</RadioGroup>
									{formik.touched["assetId"] &&
										formik.errors["assetId"] && (
											<div className="text-sm text-red-500">
												{formik.errors["assetId"]}
											</div>
										)}
								</FormControl>
							)}

							<Button
								type="submit"
								variant="contained"
								loading={formik.isSubmitting}
								disabled={!formik.isValid}
							>
								Сгенерировать
							</Button>
						</div>
					</form>
				</div>
			)}
		</DialogContent>
	);
};
