import { useQueryClient } from "@tanstack/react-query";
import { CheckCircle, AlertTriangle } from "lucide-react";
import { FC, useState } from "react";
import { useTranslation } from "react-i18next";

// import { useDialogStore } from "@/contexts/dialog/lib/useDialogStore";
import { CheckListType } from "@/contracts/client.schemas";
import { useIdentityStore } from "@/features";
import { Button, ConfirmDialog } from "@/shared";

import { useAlarmDialogContext } from "../../lib/useAlarmDialogContext";

import { CheckListWidget } from "./CheckListWidget";
import { PDFGenerator } from "./PDFGenerator";
import { SummaryCopier } from "./SummaryCopier";

export const AlarmConfirmationStep: FC = () => {
	const { t } = useTranslation("translation");
	const { asset, scope, next, scopeStatus, responsibleComment } =
		useAlarmDialogContext();
	const user = useIdentityStore((x) => x.user);
	// const dialogStore = useDialogStore();
	const queryClient = useQueryClient();
	const [falseAlarmReason, setFalseAlarmReason] = useState("");
	const [comment, setComment] = useState("");
	const [isProcessing, setIsProcessing] = useState(false);
	const [allItemsChecked, setAllItemsChecked] = useState(false);
	const [showConfirmDialog, setShowConfirmDialog] = useState(false);
	const [pendingAction, setPendingAction] = useState<
		(() => Promise<void> | void) | null
	>(null);
	const falseAlarmReasons = [
		{ value: "technical", label: t("technicalFailure") },
		{ value: "dust", label: t("dust") },
		{ value: "maintenance", label: t("maintenanceWork") },
		{ value: "human_factor", label: t("humanFactor") },
		{ value: "other", label: t("other") },
	];

	const handleConfirmAction = async (confirmed: boolean) => {
		setShowConfirmDialog(false);
		if (confirmed && pendingAction) {
			await pendingAction();
		}
		setPendingAction(null);
	};

	const triggerConfirm = (action: () => Promise<void> | void) => {
		setPendingAction(() => action);
		setShowConfirmDialog(true);
	};

	const handleResolveAlarms = async () => {
		if (!user) {
			throw new Error("user is null");
		}

		setIsProcessing(true);

		try {
			await next();

			await queryClient.invalidateQueries({ queryKey: ["alarms"] });
			await queryClient.invalidateQueries({ queryKey: ["alarm"] });

			// TODO: fix it
			// const resolvedCount = alarms.length;
			// const finalComment = [
			// 	responsibleComment,
			// 	scopeStatus === "RealAlarm"
			// 		? "✅ Тревога подтверждена"
			// 		: `❌ Ложная тревога: ${falseAlarmReasons.find((r) => r.value === falseAlarmReason)?.label}`,
			// 	comment,
			// ]
			// 	.filter(Boolean)
			// 	.join("\n");
		} catch (error) {
			console.error(t("errorResolvingAlarms"), error);
			console.error(t("failedToCompleteProcessing"));
		} finally {
			setIsProcessing(false);
		}
	};

	if (scopeStatus === "CallsCompleted") {
		return (
			<div className="flex min-h-[400px] flex-col items-center justify-center space-y-6 p-8">
				<div className="mb-6 space-y-3 text-center">
					<h2 className="text-2xl font-bold text-gray-800">
						{t("verificationResult")}
					</h2>
					<p className="text-gray-600">
						{t("selectAlarmStatusBasedOnCheck")}
					</p>
				</div>

				<div className="grid w-full grid-cols-2 gap-6">
					<button
						onClick={() => triggerConfirm(() => next(true))}
						className="group relative border-2 border-red-300 rounded-lg p-8 hover:border-red-500 hover:bg-red-50 transition-all cursor-pointer"
					>
						<div className="flex flex-col items-center space-y-4">
							<div className="flex h-20 w-20 items-center justify-center rounded-full bg-red-100 transition-colors group-hover:bg-red-200">
								<CheckCircle className="h-12 w-12 text-red-600" />
							</div>
							<div className="text-center">
								<h3 className="mb-2 text-xl font-bold text-red-900">
									{t("alarmConfirmed")}
								</h3>
								<p className="text-sm text-gray-600">
									{t("incidentRealRequiresIntervention")}
								</p>
							</div>
						</div>
					</button>

					<button
						onClick={() => triggerConfirm(() => next(false))}
						className="group relative border-2 border-yellow-300 rounded-lg p-8 hover:border-yellow-500 hover:bg-yellow-50 transition-all cursor-pointer"
					>
						<div className="flex flex-col items-center space-y-4">
							<div className="flex h-20 w-20 items-center justify-center rounded-full bg-yellow-100 transition-colors group-hover:bg-yellow-200">
								<AlertTriangle className="h-12 w-12 text-yellow-600" />
							</div>
							<div className="text-center">
								<h3 className="mb-2 text-xl font-bold text-gray-900">
									{t("falseAlarm")}
								</h3>
								<p className="text-sm text-gray-600">
									{t("incidentNotConfirmed")}
								</p>
							</div>
						</div>
					</button>
				</div>
				<ConfirmDialog
					open={showConfirmDialog}
					onOpenChange={setShowConfirmDialog}
					onConfirm={() => handleConfirmAction(true)}
				/>
			</div>
		);
	}

	if (scopeStatus === "CommentAndSend") {
		if (scope.result === "Real") {
			return (
				<div className="flex h-full w-full flex-col overflow-hidden">
					<div className="flex-shrink-0 space-y-3 p-6 pb-4 text-center">
						<div className="mx-auto mb-4 flex h-20 w-20 items-center justify-center rounded-full bg-red-100">
							<CheckCircle className="h-12 w-12 text-red-600" />
						</div>
						<h2 className="text-2xl font-bold text-red-900">
							{t("alarmConfirmed")}
						</h2>
						<p className="text-gray-600">
							{t("incidentRecordedRequiresFurtherActions")}
						</p>
					</div>

					<div className="flex-1 space-y-4 overflow-y-auto px-6">
						<CheckListWidget
							alarmScopeId={scope.id}
							type={CheckListType.ByRealAlarm}
							onChange={setAllItemsChecked}
						/>

						<div>
							<label className="mb-2 block text-sm font-medium">
								{t("commentRequired")}
							</label>
							<textarea
								value={comment}
								onChange={(e) => setComment(e.target.value)}
								className="w-full p-3 border rounded-lg resize-none"
								rows={4}
								placeholder={t(
									"describeSituationMeasuresTaken",
								)}
								required
							/>
						</div>

						{responsibleComment && (
							<div className="rounded-lg border border-blue-200 bg-blue-50 p-3">
								<p className="mb-1 text-sm font-medium text-blue-900">
									{t("callHistory")}
								</p>
								<p className="text-sm whitespace-pre-line text-blue-800">
									{responsibleComment}
								</p>
							</div>
						)}
					</div>

					<div className="flex-shrink-0 space-y-3 border-t p-6 pt-4">
						<div className="flex justify-center gap-3">
							<PDFGenerator
								checkListType={CheckListType.ByRealAlarm}
								comment={comment.trim()}
							/>
							{user && asset && (
								<SummaryCopier
									comment={comment.trim()}
									user={user}
									scopeId={scope.id}
								/>
							)}
						</div>
						<div className="flex justify-center">
							<Button
								size="lg"
								onClick={() =>
									triggerConfirm(handleResolveAlarms)
								}
								disabled={
									isProcessing ||
									!allItemsChecked ||
									!comment.trim()
								}
								className="bg-red-600 px-8 hover:bg-red-700"
							>
								{isProcessing
									? t("completing")
									: t("completed_description")}
							</Button>
						</div>
					</div>
					<ConfirmDialog
						open={showConfirmDialog}
						onOpenChange={setShowConfirmDialog}
						onConfirm={() => handleConfirmAction(true)}
					/>
				</div>
			);
		}

		if (scope.result === "False") {
			return (
				<div className="flex h-full w-full flex-col overflow-hidden">
					<div className="flex-shrink-0 space-y-3 p-6 pb-4 text-center">
						<div className="mx-auto mb-4 flex h-20 w-20 items-center justify-center rounded-full bg-yellow-100">
							<AlertTriangle className="h-12 w-12 text-yellow-600" />
						</div>
						<h2 className="text-2xl font-bold text-gray-800">
							{t("falseAlarm")}
						</h2>
						<p className="text-gray-600">
							{t("specifyReasonForFalseAlarm")}
						</p>
					</div>

					<div className="flex-1 space-y-4 overflow-y-auto px-6">
						<CheckListWidget
							alarmScopeId={scope.id}
							type={CheckListType.ByFalseAlarm}
							onChange={setAllItemsChecked}
						/>

						<div>
							<label className="mb-2 block text-sm font-medium">
								{t("falseAlarmReasonRequired")}
							</label>
							<select
								value={falseAlarmReason}
								onChange={(e) =>
									setFalseAlarmReason(e.target.value)
								}
								className="w-full p-3 border rounded-lg"
							>
								<option value="">{t("chooseReason")}</option>
								{falseAlarmReasons.map((reason) => (
									<option
										key={reason.value}
										value={reason.value}
									>
										{reason.label}
									</option>
								))}
							</select>
						</div>

						<div>
							<label className="mb-2 block text-sm font-medium">
								{t("commentRequired")}
							</label>
							<textarea
								value={comment}
								onChange={(e) => setComment(e.target.value)}
								className="w-full p-3 border rounded-lg resize-none"
								rows={4}
								placeholder={t(
									"detailedDescriptionOfSituation",
								)}
								required
							/>
						</div>

						{responsibleComment && (
							<div className="rounded-lg border border-blue-200 bg-blue-50 p-3">
								<p className="mb-1 text-sm font-medium text-blue-900">
									{t("callHistory")}
								</p>
								<p className="text-sm whitespace-pre-line text-blue-800">
									{responsibleComment}
								</p>
							</div>
						)}

						<div className="rounded-lg border border-yellow-200 bg-yellow-50 p-3 text-sm text-yellow-800">
							{t("systemCheckRequiredAfterCompletion")}
						</div>
					</div>

					<div className="flex flex-shrink-0 justify-center border-t p-6 pt-4">
						<Button
							size="lg"
							onClick={() => triggerConfirm(handleResolveAlarms)}
							disabled={
								!falseAlarmReason ||
								!comment.trim() ||
								isProcessing ||
								!allItemsChecked
							}
							className="bg-yellow-600 px-8 hover:bg-yellow-700"
						>
							{isProcessing
								? t("completing")
								: t("completeAsFalse")}
						</Button>
					</div>
					<ConfirmDialog
						open={showConfirmDialog}
						onOpenChange={setShowConfirmDialog}
						onConfirm={() => handleConfirmAction(true)}
					/>
				</div>
			);
		}
	}

	return null;
};
