import { Stack } from "@mui/material";
import dayjs from "dayjs";
import { useTranslation } from "react-i18next";

import { AreaModel } from "@/contracts/client.schemas";
import { useWatcherStore } from "@/modules/watcher/store/watcher.store";
import { TableInfinity } from "@/shared";

import styles from "./AssetState.module.css";

const goodStateTitle = "Normal";
const hasAlarmsTitle = "Has alarms";
const goodStateTitleClassName = "good-state-title";
const hasAlarmsTitleClassName = "has-alarms-title";

export function AssetState() {
	const { t } = useTranslation("translation");
	const { t: tContactId } = useTranslation("contact_id");
	const areas = useWatcherStore((x) => x.assetAreas);
	areas.sort((a, b) => a.index - b.index);
	const getAlarms = useWatcherStore((x) => x.assetAlarms);
	const alarms = getAlarms();
	const hasAlarms = alarms.length > 0;
	const events = useWatcherStore((x) => x.assetEvents);
	events.sort(
		(a, b) => dayjs(b.createdAt).unix() - dayjs(a.createdAt).unix(),
	);

	function getAreaNote(area: AreaModel) {
		const areaEvents = events.filter((x) => x.areaIndex === area.index);
		if (areaEvents.length === 0) {
			return "-";
		}

		type ContactIdKey = (typeof tContactId.arguments)[0];
		return tContactId(areaEvents[0].code.toString() as ContactIdKey);
	}

	return (
		<Stack spacing={2}>
			<Stack direction="row" spacing={1} alignItems="center">
				<span>{t("State: ")}</span>
				<span
					className={
						styles[
							hasAlarms
								? hasAlarmsTitleClassName
								: goodStateTitleClassName
						]
					}
				>
					{hasAlarms ? t(hasAlarmsTitle) : t(goodStateTitle)}
				</span>
			</Stack>

			<TableInfinity
				columns={[
					{
						label: t("area"),
						width: 1,
					},
					{
						label: t("Notes"),
						width: 3,
					},
				]}
				rows={areas.map((x) => ({
					values: [x.name, getAreaNote(x)],
				}))}
			/>
		</Stack>
	);
}
