import { CheckCircle, Warning } from "@mui/icons-material";
import { Button, Typography } from "@mui/material";
import { FC } from "react";
import { useEmitter } from "react-eventizer";
import { useTranslation } from "react-i18next";

import { useAlarmStore } from "@/store/alarm.store";

import { NoConnectionIcon } from "../common/components/Icons/NoConnectionIcon";
import { maxPingDelaySeconds } from "../constants";
import { usePingStore } from "../modules/watcher/store/ping.store";

interface Props {
	useFullWidth: boolean;
}

export const ObjectsWatcher: FC<Props> = ({ useFullWidth }) => {
	const { t } = useTranslation();
	const { isServerConnected } = usePingStore();
	const countOfAlarmScopes = useAlarmStore((x) => x.countOfAlarmScopes);
	const emit = useEmitter("OBJECTWATCHER.CLICK");

	const hasAlarms = countOfAlarmScopes !== 0;
	const color = hasAlarms ? "error-500" : "success-500";
	const title = hasAlarms
		? t("objectsWithAlarms", { count: countOfAlarmScopes })
		: t("allObjectsAreGood");

	const icon = hasAlarms ? <Warning /> : <CheckCircle />;

	if (!isServerConnected) {
		if (useFullWidth) {
			return (
				<Typography
					variant="body1"
					className="text-nowrap"
					color="error"
				>
					{t(
						"Server is not available for more than {seconds} seconds",
						{ seconds: maxPingDelaySeconds },
					)}
				</Typography>
			);
		}

		return <NoConnectionIcon />;
	}

	function handleClick() {
		if (!hasAlarms) {
			return;
		}

		emit();
	}

	return (
		<Button
			variant="contained"
			onClick={handleClick}
			sx={{
				textTransform: "none",
				backgroundColor: `var(--${color})`,
				boxShadow: "none",
				borderRadius: "10px",
				padding: "10px 15px",
				gap: "10px",
			}}
		>
			{icon}
			{useFullWidth && (
				<Typography variant="body1" className="text-nowrap mx-2">
					{title}
				</Typography>
			)}
		</Button>
	);
};
