import { Typography } from "@mui/material";
import { HttpStatusCode } from "axios";
import { useParams } from "react-router-dom";
import { toast } from "react-toastify";
import { z } from "zod";

import { Card, ErrorContext } from "@/common/components/card/Card";
import { CardField } from "@/common/components/card/CardField";
import { MAX_NAME_LENGTH, MAX_TEXT_LENGTH } from "@/constants";
import { ZoneModel } from "@/contracts/client.schemas";

const validationSchema = z.object({
	index: z
		.number({
			required_error: "Index is required",
			invalid_type_error: "Index must be a number",
		})
		.min(0, "Index must be greater than or equal to 0")
		.max(255, "Index must be less than or equal to 255"),

	name: z
		.string({
			required_error: "Name is required",
			invalid_type_error: "Name must be a string",
		})
		.min(3, "Name must be at least 3 characters")
		.max(
			MAX_NAME_LENGTH,
			`Name must be less than ${MAX_NAME_LENGTH} characters`,
		),

	description: z
		.string({
			required_error: "Description is required",
			invalid_type_error: "Description must be a string",
		})
		.min(3, "Description must be at least 3 characters")
		.max(
			MAX_TEXT_LENGTH,
			`Description must be less than ${MAX_TEXT_LENGTH} characters`,
		),

	areaId: z.string().nullable(),
});

export const ZoneCardPage = () => {
	const { assetId, areaId } = useParams();
	if (!assetId) {
		throw new Error("assetId is required");
	}

	if (!areaId) {
		throw new Error("areaId is required");
	}

	const fields: CardField<ZoneModel>[] = [
		{
			name: "index",
			title: "Index",
			type: "number",
			required: true,
		},
		{
			name: "name",
			title: "Name",
			required: true,
		},
		{
			name: "description",
			title: "Description",
			type: "multiline",
			required: true,
		},
	];

	const defaultValue: ZoneModel = {
		id: "",
		name: "",
		description: "",
		areaId,
		index: 0,
		hasAlarms: false,
		hasFaults: false,
	};

	const extraTitle = (zone: ZoneModel) => {
		return <Typography>{zone.name}</Typography>;
	};

	const handleError = (error: ErrorContext) => {
		if (error.status === HttpStatusCode.Conflict) {
			toast.error("The same zone is already in the system");
			return true;
		}

		return false;
	};

	return (
		<Card
			defaultValue={defaultValue}
			fields={fields}
			baseUrl="/api/zones"
			createTitle="Добавление зоны"
			editTitle="Редактирование зоны"
			viewTitle="Карточка зоны"
			validationSchema={validationSchema}
			extraTitle={extraTitle}
			onError={handleError}
			notificationMethodPrefix="ZONES"
			getModelTitle={(x) => x.name}
			filters={{
				areaId,
			}}
			canEdit={true}
			canRemove={true}
		/>
	);
};
