import { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Pie, PieChart, ResponsiveContainer, Tooltip } from "recharts";

import { useGetCountOfEvents } from "@/contracts/analytics";
import {
	CountOfEventsItemResponseModel,
	CountOfEventsType,
} from "@/contracts/client.schemas";
import { ChartContainer } from "@/shared";

type Props = {
	type: CountOfEventsType;
	titleKey: string;
	controls?: ReactNode;
};

export const EventsOfTime = ({ type, titleKey, controls }: Props) => {
	const { data, isFetching } = useGetCountOfEvents({ Type: type });
	const { t } = useTranslation("translation");

	function getTotalCount(arr?: CountOfEventsItemResponseModel[]) {
		return arr?.reduce((acc, item) => acc + item.count, 0) ?? 0;
	}

	return (
		<ChartContainer
			titleKey={titleKey}
			isFetching={isFetching}
			controls={controls}
		>
			<div className="w-full h-full flex flex-col items-stretch">
				<div className="flex flex-col items-center">
					<div className="text-sm text-[var(--white)] bg-[var(--primary-600)] w-full text-center">
						<span>{t("Events")}:</span>
						<span className="ml-2 font-bold">
							{getTotalCount(data?.events)}
						</span>
					</div>
					<div className="text-sm text-[var(--white)] bg-[var(--error-600)] w-full text-center">
						<span>{t("Alarms")}:</span>
						<span className="ml-2 font-bold">
							{getTotalCount(data?.alarms)}
						</span>
					</div>
					<div className="text-sm text-[var(--white)] bg-[var(--error-300)] w-full text-center">
						<span>{t("Faults")}:</span>
						<span className="ml-2 font-bold">
							{getTotalCount(data?.faults)}
						</span>
					</div>
					<div className="text-sm text-[var(--white)] bg-[var(--success-600)] w-full text-center">
						<span>{t("Actions")}:</span>
						<span className="ml-2 font-bold">
							{getTotalCount(data?.operatorActions)}
						</span>
					</div>
				</div>

				<ResponsiveContainer width="100%" height="100%">
					<PieChart width={200} height={200}>
						<Pie
							data={data?.events}
							dataKey="count"
							outerRadius={50}
							cx="50%"
							cy="50%"
							fill="var(--primary-600)"
						/>
						<Pie
							data={data?.alarms}
							dataKey="count"
							innerRadius={55}
							outerRadius={70}
							cx="50%"
							cy="50%"
							fill="var(--error-600)"
						/>
						<Pie
							data={data?.faults}
							dataKey="count"
							innerRadius={75}
							outerRadius={90}
							cx="50%"
							cy="50%"
							fill="var(--error-300)"
						/>
						<Pie
							data={data?.operatorActions}
							dataKey="count"
							innerRadius={95}
							outerRadius={110}
							cx="50%"
							cy="50%"
							fill="var(--success-600)"
						/>
						<Tooltip />
					</PieChart>
				</ResponsiveContainer>
			</div>
		</ChartContainer>
	);
};
