import { useTranslation } from "react-i18next";

import { useGetCheckListByAlarmScope } from "@/contracts/check-list";
import { useGetCheckListTemplateList } from "@/contracts/check-list-template";
import { CheckListType } from "@/contracts/client.schemas";
import { useIdentityStore } from "@/features";
import { Button } from "@/shared/Button";

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

type Props = {
	checkListType: CheckListType;
	comment: string;
};

export function PDFGenerator({ checkListType, comment }: Props) {
	const { t } = useTranslation("translation");
	const { alarms, zones, areas, asset, responsibleComment } =
		useAlarmDialogContext();
	const { user } = useIdentityStore();
	const { data: checklist, isLoading: isLoadingChecklist } =
		useGetCheckListByAlarmScope(alarms?.[0]?.scopeId || "");
	const { data: templates, isLoading: isLoadingTemplates } =
		useGetCheckListTemplateList({
			Type: checkListType,
		});

	const handleGeneratePDF = () => {
		const alarm = alarms[0];
		const zone = zones?.find((z) => z.id === alarm?.zoneId);
		const area = areas?.find((a) => a.id === zone?.areaId);

		const win = window.open("", "_blank");
		if (!win) return;

		const title = `${t("transferToOperationalService")} — ${t("alarmConfirmed")}`;
		const now = new Date().toLocaleString();

		const checklistHtml =
			checklist?.items && checklist.items.length > 0
				? checklist.items
						.map((item) => {
							const template = templates?.items
								.find(
									(t) => t.type === CheckListType.ByRealAlarm,
								)
								?.items.find(
									(ti) => ti.id === item.templateItemId,
								);
							const translation =
								template?.translations.find(
									(tr) => tr.languageCode === "ru",
								) || template?.translations[0];
							return `<li>${item.isChecked ? "✓" : "○"} ${translation?.name || t("defaultCheckListItem")}</li>`;
						})
						.join("")
				: "";

		const html = `<!doctype html>
			<html lang="ru">
			<head>
				<meta charset="utf-8" />
				<meta name="viewport" content="width=device-width, initial-scale=1" />
				<title>${title}</title>
				<style>
					*{box-sizing:border-box;margin:0;padding:0}
					body{font-family:Arial,Helvetica,sans-serif;color:#111;padding:24px;background:#f9f9f9}
					h1{font-size:22px;margin:0 0 16px;color:#c00;border-bottom:2px solid #c00;padding-bottom:8px}
					h2{font-size:16px;margin:16px 0 8px;color:#333;border-bottom:1px solid #ddd;padding-bottom:4px}
					.card{background:#fff;border:1px solid #ddd;border-radius:8px;padding:16px;margin-bottom:16px;box-shadow:0 2px 4px rgba(0,0,0,0.1)}
					.info-grid{display:grid;grid-template-columns:150px 1fr;gap:8px;margin-bottom:8px}
					.label{font-weight:600;color:#555}
					.value{color:#111}
					.section{margin-bottom:12px}
					ul{margin:8px 0 0 20px;line-height:1.6}
					.footer{margin-top:24px;font-size:11px;color:#666;text-align:center;border-top:1px solid #ddd;padding-top:8px}
					.call-log{background:#f5f5f5;padding:8px;border-left:3px solid #4CAF50;margin:4px 0;border-radius:4px}
				</style>
			</head>
			<body>
				<h1>🚨 ${title}</h1>
				
				<div class="card">
					<h2>📍 ${t("objectInformation")}</h2>
					<div class="section">
						<div class="info-grid">
							<div class="label">${t("objectLabel")}</div>
							<div class="value">${asset?.name || t("notSpecified")}</div>
						</div>
						${
							asset?.description
								? `
						<div class="info-grid">
							<div class="label">${t("description")}</div>
							<div class="value">${asset.description}</div>
						</div>`
								: ""
						}
						<div class="info-grid">
							<div class="label">${t("address")}</div>
							<div class="value">${formatAddress(asset) === "addressNotSpecified" ? t("addressNotSpecified") : formatAddress(asset)}</div>
						</div>
						<div class="info-grid">
							<div class="label">${t("coordinates")}</div>
							<div class="value">${asset?.latitude && asset?.longitude ? `${asset.latitude}, ${asset.longitude}` : t("coordinatesNotSpecified")}</div>
						</div>
						${
							area
								? `
						<div class="info-grid">
							<div class="label">${t("section")}</div>
							<div class="value">${area.name}</div>
						</div>`
								: ""
						}
						${
							zone
								? `
						<div class="info-grid">
							<div class="label">${t("zone")}</div>
							<div class="value">${zone.name}</div>
						</div>`
								: ""
						}
					</div>
				</div>
	
				<div class="card">
					<h2>🔥 ${t("alarmInformation")}</h2>
					<div class="section">
						<div class="info-grid">
							<div class="label">${t("arrivalTime")}</div>
							<div class="value">${new Date(alarm?.event?.createdAt).toLocaleString("ru-RU")}</div>
						</div>
						<div class="info-grid">
							<div class="label">${t("type")}</div>
							<div class="value">${t("alarmConfirmed")}</div>
						</div>
						<div class="info-grid">
							<div class="label">${t("processedBy")}</div>
							<div class="value">${user?.username || t("operator")}</div>
						</div>
					</div>
				</div>
	
				${
					responsibleComment
						? `
				<div class="card">
					<h2>📞 ${t("callHistory")}</h2>
					<div class="section">
						${responsibleComment
							.split("\n")
							.map((line) =>
								line.trim()
									? `<div class="call-log">${line}</div>`
									: "",
							)
							.join("")}
					</div>
				</div>`
						: ""
				}
	
				${
					checklistHtml
						? `
				<div class="card">
					<h2>✓ ${t("completedActions")}</h2>
					<div class="section">
						<ul>${checklistHtml}</ul>
					</div>
				</div>`
						: ""
				}
	
				<div class="card">
					<h2>💬 ${t("operatorComment")}</h2>
					<div class="section">
						<div class="value" style="white-space: pre-line; line-height: 1.6">${comment}</div>
					</div>
				</div>
	
				<div class="footer">
					${t("documentGenerated")} ${now} | ${t("monitoringSystem")}
				</div>
				
				<script>
					window.onload = function(){
						window.focus();
						window.print();
					};
					window.onafterprint = function(){
						window.close();
					};
				</script>
			</body>
			</html>`;

		win.document.open();
		win.document.write(html);
		win.document.close();
	};

	return (
		<Button
			variant="outline"
			size="sm"
			onClick={handleGeneratePDF}
			disabled={isLoadingTemplates || isLoadingChecklist}
			className="px-6"
		>
			{t("generatePdf")}
		</Button>
	);
}
