import { useTranslation } from "react-i18next";

import { useGetCheckListByAlarmScope } from "@/contracts/check-list";
import { useGetCheckListTemplateById } from "@/contracts/check-list-template";
import { UserModel } from "@/contracts/client.schemas";
import { useContactId } from "@/hooks/use-contact-id";
import { Button } from "@/shared/Button";

import { formatAddress } from "../../lib/address-formatter";
import { useAlarmDialogContext } from "../../lib/useAlarmDialogContext";

export function SummaryCopier({
	comment,
	user,
	scopeId,
}: {
	comment: string;
	user: UserModel;
	scopeId: string;
}) {
	const { t } = useTranslation("translation");
	const { getMessage } = useContactId();
	const { alarms, zones, areas, asset, responsibleComment } =
		useAlarmDialogContext();

	const { data: checkList } = useGetCheckListByAlarmScope(scopeId);

	const checkListTemplateId = checkList?.templateId;
	const { data: checkListTemplate } = useGetCheckListTemplateById(
		checkListTemplateId!,
		{
			query: {
				enabled: !!checkListTemplateId,
			},
		},
	);

	const areaIndexList = alarms?.map((alarm) => alarm.event.areaIndex);
	const zoneIndexList = alarms?.map((alarm) => alarm.event.zoneIndex);

	const areaTitleList = areaIndexList.map(
		(index) => areas.find((x) => x.index === index)?.name,
	);
	const zoneTitleList = zoneIndexList.map(
		(index) => zones.find((x) => x.index === index)?.name,
	);

	const areaTitle = areaTitleList.join(", ");
	const zoneTitle = zoneTitleList.join(", ");

	const handleCopySummary = () => {
		const checklistText =
			checkList?.items && checkList.items.length > 0
				? checkList.items
						.map((item) => {
							const template = checkListTemplate?.items.find(
								(t) => t.id === item.templateItemId,
							);
							const translation =
								template?.translations.find(
									(tr) => tr.languageCode === "ru",
								) || template?.translations[0];
							return `  ${item.isChecked ? "✓" : "○"} ${translation?.name || "Пункт чек-листа"}`;
						})
						.join("\n")
				: "";

		const alarmsInfo = alarms?.map((alarm) => {
			return `${t("arrivalTime")} ${new Date(alarm?.event?.createdAt).toLocaleString("ru-RU")}\n${t("type")} ${getMessage(alarm.event.code)}`;
		});

		const clipboardSummary = `
${t("transferHeader")}
═══════════════════════════════════════════════════════

${t("objectInformation")}
────────────────────────────────────────
${t("objectLabel")} ${asset?.name || t("notSpecified")}${asset?.description ? `\n${t("description")} ${asset.description}` : ""}
${t("address")} ${formatAddress(asset) === "addressNotSpecified" ? t("addressNotSpecified") : formatAddress(asset)}
${t("coordinates")} ${asset?.latitude && asset?.longitude ? `${asset.latitude}, ${asset.longitude}` : t("coordinatesNotSpecified")}${areaTitle ? `\n${t("section")} ${areaTitle}` : ""}${zoneTitle ? `\n${t("zones")} ${zoneTitle}` : ""}

${t("alarmInformation")}
────────────────────────────────────────
${alarmsInfo.join("\n")}

${t("processedBy")} ${user?.username || t("operator")}

${
	responsibleComment && responsibleComment.trim()
		? `📞 ${t("callHistory")}
────────────────────────────────────────
${responsibleComment}

`
		: ""
}
}${
			checklistText
				? `✓ ${t("completedActions")}
────────────────────────────────────────
${checklistText}

`
				: ""
		}💬 ${t("operatorComment")}
────────────────────────────────────────
${comment}

───────────────────────────────────────────────────────
${t("documentGenerated")} ${new Date().toLocaleString("ru-RU")}
		`.trim();

		navigator.clipboard.writeText(clipboardSummary);
		alert(t("summaryCopied"));
	};

	return (
		<Button
			variant="outline"
			size="sm"
			onClick={handleCopySummary}
			className="px-6"
		>
			📋 {t("copySummary")}
		</Button>
	);
}
