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

import { Column, createColumn } from "@/common/components/Matrix/Column";
import { Matrix } from "@/common/components/Matrix/Matrix";
import type {
	GetCommentListResponse,
	TranslateComment,
} from "@/contracts/client.schemas";

export const AlarmDescriptionListPage = () => {
	const { organizationId } = useParams<{ organizationId: string }>();
	const { i18n, t } = useTranslation();

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

	const getTranslated = (translates: TranslateComment[]) => {
		if (!translates || !Array.isArray(translates)) {
			return "";
		}

		const langCode = i18n.language.split("-")[0];

		const tr = translates.find((x) => x.language === langCode);

		if (!tr) {
			const trPartial = translates.find((x) =>
				x.language.startsWith(langCode),
			);
			if (trPartial) {
				return trPartial.value;
			}
		}

		if (!tr && translates.length > 0) {
			return translates[0].value;
		}

		const result = tr ? tr.value : "";
		return result;
	};

	const columns: Column<GetCommentListResponse>[] = [
		createColumn<GetCommentListResponse, "translates">(
			"Reason",
			"translates",
			(value) => {
				return getTranslated(value);
			},
		),
	];

	const filters = { organizationId, lang: i18n.language.split("-")[0] };

	return (
		<Matrix<GetCommentListResponse>
			columns={columns}
			title={t("reasonReset")}
			baseUrl="/api/alarm-reset-comments"
			filters={filters}
			canCreate={true}
			canRemove={true}
			canView={true}
			notificationMethodPrefix="ALARM-RESET-COMMENTS"
			getModelTitle={(model) => {
				return getTranslated(model.translates);
			}}
		/>
	);
};
