import { CheckCircle, AlertTriangle } from "lucide-react";
import { FC, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

import { useGetCallList } from "@/contracts/calls";
import { ConfirmDialog } from "@/shared";

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

export const SelectAlarmRealityStep: FC = () => {
	const { t } = useTranslation("translation");
	const { scope, next, scopeStatus } = useAlarmDialogContext();
	const [showConfirmDialog, setShowConfirmDialog] = useState(false);
	const [pendingAction, setPendingAction] = useState<
		(() => Promise<void> | void) | null
	>(null);
	const [autoTransitionDone, setAutoTransitionDone] = useState(false);

	const { data: callsData, isFetched } = useGetCallList({
		AlarmScopeId: scope.id,
	});

	// Автопереход на реальную тревогу, если ответственный подтвердил
	useEffect(() => {
		if (
			scopeStatus === "CallsCompleted" &&
			isFetched &&
			callsData &&
			!autoTransitionDone
		) {
			const hasConfirmedRealAlarm = callsData.items.some(
				(call) => call.isConfirmedRealAlarm === true,
			);
			if (hasConfirmedRealAlarm) {
				setAutoTransitionDone(true);
				next(true);
			}
		}
	}, [scopeStatus, callsData, isFetched, autoTransitionDone, next]);

	// Показываем лоадер пока проверяем звонки на этапе выбора
	if (!isFetched) {
		return (
			<div className="flex min-h-[400px] flex-col items-center justify-center">
				<div className="h-8 w-8 animate-spin rounded-full border-4 border-gray-300 border-t-blue-600" />
			</div>
		);
	}

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

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

	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>
	);
};
