import { useTranslation } from "react-i18next";
import { useParams } from "react-router-dom";
import { z } from "zod";

import {
	GetCommentResponse,
	TranslateComment,
} from "@/contracts/client.schemas";
import { LANGUAGES } from "@/i18n/config";

import { Card } from "../../../common/components/card/Card";

export const AlarmDescriptionCardPage = () => {
	const { organizationId, id = "new" } = useParams<{
		organizationId: string;
		id: string;
	}>();
	const { t, i18n } = useTranslation("translation");

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

	const supportedLanguages = LANGUAGES.map((code) => ({
		code,
		name: t(`languages.${code}`, { defaultValue: code.toUpperCase() }),
	}));

	type FlatFormData = {
		id: string;
		organizationId: string;
	} & Record<string, string>;

	const defaultValue: FlatFormData = {
		id: id === "new" ? "" : id,
		organizationId,
		...supportedLanguages.reduce(
			(acc, lang) => {
				acc[lang.code] = "";
				return acc;
			},
			{} as Record<string, string>,
		),
	};

	const schema = z.object({
		id: z.string(),
		organizationId: z.string(),
		...(Object.fromEntries(
			supportedLanguages.map(({ code }) => [
				code,
				z.string().min(1, t("validation.required")),
			]),
		) as Record<string, z.ZodString>),
	});

	const onLoaded = (apiDataUnknown: unknown): FlatFormData => {
		const apiData = apiDataUnknown as GetCommentResponse;
		const existingTranslates = apiData.translates || [];
		const flatData: FlatFormData = {
			id: apiData.id,
			organizationId: apiData.organizationId,
		};

		supportedLanguages.forEach((lang) => {
			const existing = existingTranslates.find(
				(t) => t.language === lang.code,
			);
			flatData[lang.code] = existing?.value || "";
		});

		return flatData;
	};

	// const onSubmit = async (formData: FlatFormData): Promise<FlatFormData> => {
	// 	const translates: TranslateComment[] = [];

	// 	supportedLanguages.forEach((lang) => {
	// 		const value = formData[lang.code]?.trim();
	// 		if (value) {
	// 			translates.push({
	// 				language: lang.code,
	// 				value,
	// 			});
	// 		}
	// 	});

	// 	return {
	// 		...formData,
	// 		translates: translates as Record<string, string>,
	// 	};
	// };

	return (
		<Card<FlatFormData>
			defaultValue={defaultValue}
			canEdit={id !== "new"}
			canRemove={id !== "new"}
			createTitle={t("alarmReset.createTitle")}
			editTitle={t("alarmReset.editTitle")}
			viewTitle={t("alarmReset.viewTitle")}
			baseUrl="/api/alarm-reset-comments"
			fields={supportedLanguages.map((lang) => ({
				name: lang.code,
				title: lang.name,
				type: "input" as const,
				required: true,
			}))}
			validationSchema={schema}
			getModelTitle={(m) => m[i18n.language.split("-")[0]] || ""}
			notificationMethodPrefix="ALARM-RESET-COMMENTS"
			onLoaded={onLoaded}
			// onSubmit={onSubmit}
		/>
	);
};
