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

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

const fields: CardField<ResponsiblePersonModel>[] = [
	{
		name: "name",
		title: "Name",
		required: true,
	},
	{
		name: "key",
		title: "Key",
	},
	{
		name: "phone1",
		title: "phone1",
	},
	{
		name: "phone2",
		title: "phone2",
	},
	{
		name: "note",
		title: "Note",
		type: "multiline",
	},
];

const createNameValidator = (name: string) => {
	return z
		.string({
			invalid_type_error: `${name} must be a string`,
		})
		.max(
			MAX_NAME_LENGTH,
			`${name} must be less than ${MAX_NAME_LENGTH} characters`,
		);
};

const validationSchema = z.object({
	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`,
		),

	key: createNameValidator("key"),
	phone1: createNameValidator("phone1"),
	phone2: createNameValidator("phone2"),

	note: z
		.string({
			invalid_type_error: "Note must be a string",
		})
		.max(
			MAX_TEXT_LENGTH,
			`Note must be less than ${MAX_TEXT_LENGTH} characters`,
		)
		.optional(),
});

export const ResponsiblePersonCardPage = () => {
	const { assetId } = useParams();

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

	const defaultValue: ResponsiblePersonModel = {
		id: "",
		name: "",
		key: "",
		phone1: "",
		phone2: "",
		note: "",
		assetId: "",
	};

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

	return (
		<Card
			defaultValue={defaultValue}
			fields={fields}
			baseUrl="/api/responsible-persons"
			createTitle="Добавление ответственного лица"
			editTitle="Редактирование ответственного лица"
			viewTitle="Карточка ответственного лица"
			validationSchema={validationSchema}
			extraTitle={extraTitle}
			filters={{
				assetId,
			}}
			getModelTitle={(model) => model.name}
			notificationMethodPrefix="RESPONSIBLE-PERSONS"
			canEdit={true}
			canRemove={true}
		/>
	);
};
