import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

import { useIdentityStore, useAudioStore } from "@/features";
import { Button, ConfirmDialog } from "@/shared";

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

export function AcceptAlarmStep() {
	const { t } = useTranslation("translation");
	const { alarms, next } = useAlarmDialogContext();
	const user = useIdentityStore((x) => x.user);
	const setIsPlaying = useAudioStore((x) => x.setIsPlaying);
	const [isAccepting, setIsAccepting] = useState(false);
	const [showConfirmDialog, setShowConfirmDialog] = useState(false);

	useEffect(() => {
		setIsPlaying(true);

		return () => {
			setIsPlaying(false);
		};
	}, [setIsPlaying]);

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

		setIsAccepting(true);
		setIsPlaying(false);
		await next();
		setIsAccepting(false);
	};

	const handleAcceptClick = () => {
		setShowConfirmDialog(true);
	};

	return (
		<div className="flex min-h-[400px] flex-col items-center justify-center space-y-6 p-8">
			<div className="space-y-3 text-center">
				<div className="mx-auto mb-4 flex h-20 w-20 items-center justify-center rounded-full bg-red-100">
					<div className="text-5xl text-red-600">🚨</div>
				</div>

				<h2 className="text-2xl font-bold text-gray-800">
					{t("acceptAlarmsTitle")}
				</h2>

				<p className="text-lg text-gray-600">
					{t("newAlarmsOnObject")} <strong>{alarms.length}</strong>
				</p>

				<div className="rounded-lg border border-blue-200 bg-blue-50 p-4 text-left text-sm">
					<p className="mb-2 font-medium text-blue-900">
						{t("uponAcceptance")}
					</p>
					<ul className="list-inside list-disc space-y-1 text-blue-800">
						<li>{t("allNewAlarmsWillBeAssignedToYou")}</li>
						<li>
							{t("newAlarmsDuringProcessingWillAlsoBeAssigned")}
						</li>
						<li>{t("otherOperatorsWillNotSeeTheseAlarms")}</li>
					</ul>
				</div>

				<Button
					size="lg"
					onClick={handleAcceptClick}
					disabled={isAccepting}
					className="bg-green-600 px-8 py-3 text-lg text-white hover:bg-green-700"
				>
					{isAccepting
						? t("accepting")
						: `${t("accept")} ${alarms.length === 1 ? t("alarmSingular") : t("acceptAllAlarmsText")}`}
				</Button>
			</div>

			<ConfirmDialog
				open={showConfirmDialog}
				onOpenChange={setShowConfirmDialog}
				onConfirm={handleConfirmAccept}
			/>
		</div>
	);
}
