import { Box, Button } from "@mui/material";
import { FC, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

import { useAudioStore } from "@/features";

import { useWatcher } from "../hooks/useWatcher";
import { useWatcherStore } from "../store/watcher.store";

import { EventObjectTable } from "./EventObjectTable";
import { ObjectEventDetails } from "./ObjectEventDetails";

export const EventCardDialog: FC = () => {
	const audio = useAudioStore();
	const { t } = useTranslation();
	const [, setTitle] = useState("");
	// const dialogs = useDialogsStore();
	const watcher = useWatcher();
	const watcherStore = useWatcherStore();

	useEffect(() => {
		const count = watcher.alarmedAssets.length;
		setTitle(
			count === 0
				? t("areNoUnhandledAlarms")
				: t("objectsWithAlarms", { count }),
		);

		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [watcher.alarmedAssets]);

	const currentAsset = watcherStore.assets.find(
		(x) => x.id === watcherStore.currentAssetId,
	);
	const isDisabledActionsButton = !currentAsset;
	const isDisabledResetAlarmButton =
		!currentAsset ||
		!watcher.alarmedAssets.some((x) => x.id === currentAsset.id);

	const handleActions = () => {
		if (!currentAsset) {
			throw new Error("Current asset is required");
		}

		// dialogs.open(Dialogs.EVENT_ACTIONS_CARD, {
		// 	asset: currentAsset,
		// });
	};

	const handleResetAlarm = () => {
		if (!currentAsset) {
			return;
		}

		// dialogs.open(Dialogs.ALARM_RESETTING_CARD, {
		// 	asset: currentAsset,
		// });
	};

	const handleStopSound = () => {
		audio.setIsPlaying(false);
	};

	return (
		<Box
			sx={{
				display: "flex",
				gap: 3,
				width: "100%",
				height: "100%",
			}}
		>
			{/* Left */}
			<Box
				sx={{
					display: "flex",
					flexDirection: "column",
					gap: 3,
					width: "20rem",
					height: "100%",
				}}
			>
				<Box
					sx={{
						flexGrow: 1,
					}}
				>
					<EventObjectTable />
				</Box>

				<Box
					sx={{
						display: "flex",
						flexDirection: "column",
						gap: 2,
					}}
				>
					<Button
						variant="outlined"
						color="info"
						disabled={!audio.isPlaying}
						onClick={handleStopSound}
					>
						{t("turnOffSound")}
					</Button>
					<Button
						variant="outlined"
						color="warning"
						disabled={isDisabledActionsButton}
						onClick={handleActions}
					>
						{t("actions")}
					</Button>
					<Button
						variant="outlined"
						color="error"
						disabled={isDisabledResetAlarmButton}
						onClick={handleResetAlarm}
					>
						{t("resetAlarm")}
					</Button>
				</Box>
			</Box>

			{/* Right */}
			<Box
				sx={{
					flexGrow: 1,
					width: "35rem",
					height: "100%",
				}}
			>
				{currentAsset && <ObjectEventDetails asset={currentAsset} />}
			</Box>
		</Box>
	);
};
