import dayjs from "dayjs";
import { type FC } from "react";
import { useTranslation } from "react-i18next";

import { useContactId } from "@/hooks/use-contact-id";
import { TableInfinity } from "@/shared";

import { formatDateTime } from "../../../services/time.service";
import { useNames } from "../hooks/useNames";
import { useWatcherStore } from "../store/watcher.store";

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

export const EventTable: FC = () => {
	const { t } = useTranslation("translation");
	const { getMessage } = useContactId();
	const watcher = useWatcherStore();
	const names = useNames();

	function getData() {
		const events = watcher.assetEvents;
		events.sort(
			(a, b) => dayjs(b.createdAt).unix() - dayjs(a.createdAt).unix(),
		);
		return events.map((x) => ({
			values: [
				formatDateTime(new Date(x.createdAt)),
				getMessage(x.code),
				x.areaIndex?.toFixed(0) ?? "-",
				names.getAreaName(x.areaIndex),
				// x.zoneIndex?.toFixed(0) ?? "-",
				// names.getZoneName(x.zoneIndex),
			],
			color: watcher.assetAlarms().find((a) => a.event.id === x.id)
				? "var(--error-300)"
				: undefined,
		}));
	}

	return (
		<div className={styles.container}>
			<div className={styles.title}>
				<span>{t("Total: ")}</span>
				<span className={styles.count}>
					{watcher.assetEvents.length}
				</span>
				<span>{t("Events")}</span>
			</div>
			<TableInfinity
				columns={[
					{
						label: t("timeOfReceiving"),
						width: 1,
					},
					{
						label: t("alarm"),
						width: 4,
					},
					{
						label: t("area"),
						width: 0.5,
					},
					{
						label: t("areaName"),
						width: 2,
					},
					// {
					// 	label: t("zone"),
					// 	width: 0.5,
					// },
					// {
					// 	label: t("zoneName"),
					// 	width: 2,
					// },
				]}
				rows={getData()}
			/>
		</div>
	);
};
