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

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

export const FaultsHealthSummary = () => {
	const assets = useWatcherStore((x) => x.assets);
	const faults = useWatcherStore((x) => x.commonFaults);
	const { t } = useTranslation("translation");

	const { total, withFaults, healthy, withFaultsPercent, healthyPercent } =
		useMemo(() => {
			const totalAssets = assets.length;
			const assetIdsWithFaults = new Set(
				faults.map((f) => f.event.assetId),
			);
			const withFaults = assetIdsWithFaults.size;
			const healthy = Math.max(totalAssets - withFaults, 0);

			const withFaultsPercent = totalAssets
				? Math.round((withFaults / totalAssets) * 100)
				: 0;
			const healthyPercent = 100 - withFaultsPercent;

			return {
				total: totalAssets,
				withFaults,
				healthy,
				withFaultsPercent,
				healthyPercent,
			};
		}, [assets, faults]);

	return (
		<ChartContainer titleKey={t("Faults and Health")} isFetching={false}>
			<div className="flex items-center justify-between gap-6 h-full">
				<div className="flex flex-col gap-2">
					<div className="text-base text-[var(--black-700)]">
						{t("Assets with faults")}
					</div>
					<div className="text-3xl font-bold text-[var(--error-500)]">
						{withFaultsPercent}%
					</div>
					<div className="text-sm text-[var(--black-500)]">
						{withFaults}/{total}
					</div>

					<div className="mt-4 text-base text-[var(--black-700)]">
						{t("Average health")}
					</div>
					<div className="text-3xl font-bold text-[var(--success-600)]">
						{healthyPercent}%
					</div>
					<div className="text-sm text-[var(--black-500)]">
						{healthy}/{total}
					</div>
				</div>

				<div className="flex-1 h-full flex items-center justify-center">
					<PieChart
						series={[
							{
								data: [
									{
										id: "healthy",
										value: healthy,
										label: t("Healthy"),
										color: "var(--success-400)",
									},
									{
										id: "faults",
										value: withFaults,
										label: t("With faults"),
										color: "var(--error-400)",
									},
								],
							},
						]}
						width={220}
						height={220}
						hideLegend={true}
					/>
				</div>
			</div>
		</ChartContainer>
	);
};
