import { List, ListItem, ListItemText } from "@mui/material";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";

import { useWatcherStore } from "@/modules/watcher/store/watcher.store";
import { ChartContainer } from "@/shared";

export const TopAlarmedAssets = () => {
	const alarms = useWatcherStore((x) => x.commonAlarms);
	const assets = useWatcherStore((x) => x.assets);
	const { t } = useTranslation("translation");

	const items = useMemo(() => {
		const counts = new Map<string, number>();
		for (const a of alarms) {
			const id = a.event.assetId;
			counts.set(id, (counts.get(id) ?? 0) + 1);
		}
		const result = Array.from(counts.entries())
			.map(([assetId, count]) => ({
				assetId,
				count,
				name: assets.find((x) => x.id === assetId)?.name ?? assetId,
			}))
			.sort((a, b) => b.count - a.count)
			.slice(0, 10);
		return result;
	}, [alarms, assets]);

	return (
		<ChartContainer titleKey={t("Top alarmed assets")} isFetching={false}>
			<List dense disablePadding>
				{items.map((x) => (
					<ListItem key={x.assetId} divider disableGutters>
						<ListItemText
							primary={x.name}
							secondary={`${t("Alarms")}: ${x.count}`}
						/>
					</ListItem>
				))}
				{items.length === 0 && (
					<ListItem disableGutters>
						<ListItemText primary={t("No data available")} />
					</ListItem>
				)}
			</List>
		</ChartContainer>
	);
};
