import { PieChart } from "@mui/x-charts";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

import { useGetAssetOnlineStatus } from "@/contracts/analytics";
import { ChartContainer } from "@/shared";

export const OnlineAssetsStatusPieChart = () => {
	const { data, isFetching } = useGetAssetOnlineStatus();
	const [total, setTotal] = useState(0);
	const [online, setOnline] = useState(0);
	const { t } = useTranslation();

	useEffect(() => {
		if (data) {
			setTotal(data.totalAssetsCount);
			setOnline(data.onlineAssetsCount);
		}
	}, [data]);

	const onlineInPercent = Math.round((online / total) * 100);
	const offlineInPercent = 100 - onlineInPercent;

	return (
		<ChartContainer
			titleKey={t("Online Assets Status")}
			isFetching={isFetching}
		>
			<PieChart
				series={[
					{
						data: [
							{
								id: "online",
								value: online,
								label: t("online: {{count}}", {
									count: online,
									percent: onlineInPercent,
								}),
								color: "var(--success-400)",
							},
							{
								id: "offline",
								value: total - online,
								label: t("offline: {{count}}", {
									count: total - online,
									percent: offlineInPercent,
								}),
								color: "var(--error-400)",
							},
						],
					},
				]}
				width={200}
				height={200}
			/>
		</ChartContainer>
	);
};
