import { HttpStatusCode } from "axios";
import { useTranslation } from "react-i18next";
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 { TableStateResponse } from "../../../common/models/TableStateResponse";
import { http } from "../../../services/http.service";

import { EventCode } from "./EventCode";
import { LockedEventCode } from "./LockedEventCode";

const validationSchema = z.object({
	assetId: z.string({
		required_error: "Asset ID is required",
		invalid_type_error: "Asset ID must be a string"
	}).uuid("Asset ID must be a valid UUID"),

	eventCodeId: z.string({
		required_error: "Event Code ID is required",
		invalid_type_error: "Event Code ID must be a string"
	}).uuid("Event Code ID must be a valid UUID"),
});

export const LockedEventCodeCardPage = () => {
	const { organizationId, assetId } = useParams();
	const { t } = useTranslation();

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

	function getMessage(eventCode: EventCode) {
		type ContactIdKey = (typeof t.arguments)[0];
		t(eventCode.value.toFixed(0) as ContactIdKey);
	}

	const fields: CardField<LockedEventCode>[] = [
		{
			name: "eventCodeId",
			title: "Event",
			type: "select",
			required: true,
			loadOptions: async () => {
				const response =
					await http.get<TableStateResponse<EventCode>>(
						`/api/event-codes`,
					);
				return response.items.map((x) => ({
					key: x.id,
					value: `${x.value} => ${getMessage(x)}`,
				}));
			},
		},
	];

	const defaultValue: LockedEventCode = {
		id: "",
		assetId,
		eventCodeId: "",
	};

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

		return false;
	};

	return (
		<Card
			defaultValue={defaultValue}
			fields={fields}
			baseUrl={`/api/organizations/${organizationId}/assets/${assetId}/locked-event-codes`}
			createTitle="Добавление события в черный список"
			editTitle="Редактирование события в черном списке"
			viewTitle="Карточка события в черном списке"
			validationSchema={validationSchema}
			onError={handleError}
			notificationMethodPrefix="LOCKED_EVENT_CODES"
			getModelTitle={() => "Событие в черном списке"}
			canEdit={false}
			canRemove={true}
		/>
	);
};
