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

import { Centroid } from "../../../common/components/Centroid";
import { Loader } from "../../../common/components/Loader";
import { ReactVirtualizedTable } from "../../../components/VirtualizedTable";
import { dayjsFormatDateTimeWithoutSeconds } from "../../../services/time.service";
import { Report } from "../models/Report";



interface Props {
	report: Report;
}

interface AssetReportItem {
	Id: string;
	Name: string;
	AlarmCount: number;
	TotalCount: number;
}

interface ReportData {
	From: string;
	To: string;
	Items: AssetReportItem[];
}

export const SummaryEventsReportDetails: FC<Props> = ({ report }) => {
	const { t } = useTranslation();

	const data = report?.data as string;
	if (!data) {
		return (
			<Centroid>
				<Loader />
			</Centroid>
		);
	}

	const parsedData = JSON.parse(data) as ReportData;

	function getCommonCount(items: AssetReportItem[]): number {
		return items.reduce((acc, item) => acc + item.TotalCount, 0);
	}

	function getAlarmCount(items: AssetReportItem[]): number {
		return items.reduce((acc, item) => acc + item.AlarmCount, 0);
	}

	return (
		<Stack
			spacing={2}
			sx={{ height: "100%", overflow: "hidden", width: "100%" }}
		>
			<Stack direction="row" spacing={1}>
				<Typography>{t("Отчетный период:")}</Typography>
				<Typography fontWeight="600">
					{parsedData.From &&
						dayjsFormatDateTimeWithoutSeconds(
							dayjs(parsedData.From)
						)}
				</Typography>
				<Typography fontWeight="600">-</Typography>
				<Typography fontWeight="600">
					{parsedData.To &&
						dayjsFormatDateTimeWithoutSeconds(dayjs(parsedData.To))}
				</Typography>
			</Stack>

			<Stack spacing={2} sx={{ overflow: "auto", width: "100%" }}>
				<ReactVirtualizedTable
					columns={[
						// {
						// 	fieldName: "AssetId",
						// 	titleKey: "ИД Объекта",
						// },
						{
							fieldName: "Name",
							titleKey: "Name",
						},
						{
							fieldName: "CommonCount",
							titleKey: "Количество событий",
						},
						{
							fieldName: "AlarmCount",
							titleKey: "Количество тревог",
						},
					]}
					data={parsedData.Items.map((item) => ({
						Id: item.Id,
						Name: item.Name,
						CommonCount: item.TotalCount,
						AlarmCount: item.AlarmCount,
					}))}
					height={1000}
				/>

				{/* <Typography>Отчет за период: <b>01.01.2024 00:00 - 31.12.2024 23:59</b></Typography> */}
				<Typography>
					Всего объектов: <b>{parsedData.Items.length}</b>
				</Typography>
				<Typography>
					Всего событий: <b>{getCommonCount(parsedData.Items)}</b>
				</Typography>
				<Typography>
					Всего тревог: <b>{getAlarmCount(parsedData.Items)}</b>
				</Typography>
			</Stack>
		</Stack>
	);
};
