import { z } from "zod";

import { Card } from "@/common/components/card/Card";
import { CardField } from "@/common/components/card/CardField";
import {
	CheckListTemplateModel,
	CheckListType,
} from "@/contracts/client.schemas";
import { LANGUAGES } from "@/i18n/config";

import { CheckListItemsEditor } from "./CheckListItemsEditor";

const fields: CardField<CheckListTemplateModel>[] = [
	{
		name: "type",
		title: "Type",
		required: true,
		type: "select",
		options: [
			{
				key: CheckListType.ByRealAlarm,
				value: "By real alarm",
			},
			{
				key: CheckListType.ByFalseAlarm,
				value: "By false alarm",
			},
		],
	},
];

const validationSchema = z.object({
	type: z.enum([CheckListType.ByRealAlarm, CheckListType.ByFalseAlarm]),
	items: z
		.array(
			z.object({
				index: z.number(),
				translations: z
					.array(
						z.object({
							languageCode: z.string(),
							name: z.string().min(1, "Name is required"),
							description: z.string(),
						}),
					)
					.refine(
						(translations) => {
							const codes = translations.map(
								(t) => t.languageCode,
							);
							return LANGUAGES.every((lang) =>
								codes.includes(lang),
							);
						},
						{
							message: `All languages (${LANGUAGES.join(", ")}) must be filled`,
						},
					)
					.refine(
						(translations) => {
							return translations.every(
								(t) => t.name.trim().length > 0,
							);
						},
						{
							message: "All names must be filled",
						},
					),
			}),
		)
		.optional(),
});

const defaultValue: CheckListTemplateModel = {
	id: "",
	type: CheckListType.Unknown,
	items: [],
};

export const CheckListCardPage = () => {
	return (
		<Card
			defaultValue={defaultValue}
			fields={fields}
			baseUrl="/api/check-list-templates"
			createTitle="Adding check list template"
			editTitle="Editing check list template"
			viewTitle="Check list template card"
			validationSchema={validationSchema}
			getModelTitle={(model) => model.type}
			notificationMethodPrefix="CHECK_LIST_TEMPLATES"
			canEdit={true}
			canRemove={false}
			extraFields={(_, isEdit) => (
				<CheckListItemsEditor isEdit={isEdit} />
			)}
		/>
	);
};
