"use client";

import { TrendingUp } from "lucide-react";
import * as React from "react";
import { Label, Pie, PieChart } from "recharts";

import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { type ChartConfig, ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart";

export const description = "Nutzung des Druckers";

interface ComponentProps {
	data: {
		printerId: string;
		utilizationPercentage: number;
		name: string;
	};
}

const chartConfig = {} satisfies ChartConfig;

export function PrinterUtilizationChart({ data }: ComponentProps) {
	const totalUtilization = React.useMemo(() => data.utilizationPercentage, [data]);
	const dataWithColor = {
		...data,
		fill: "rgb(34 197 94)",
	};
	const free = {
		printerId: "-",
		utilizationPercentage: 1 - data.utilizationPercentage,
		name: "(Frei)",
		fill: "rgb(212 212 212)",
	};

	return (
		<Card className="flex flex-col">
			<CardHeader className="items-center pb-0">
				<CardTitle>{data.name}</CardTitle>
				<CardDescription>Nutzung des ausgewählten Druckers</CardDescription>
			</CardHeader>
			<CardContent className="flex-1 pb-0">
				<ChartContainer config={chartConfig} className="mx-auto aspect-square max-h-[250px]">
					<PieChart>
						<ChartTooltip cursor={false} content={<ChartTooltipContent hideLabel />} />
						<Pie
							data={[dataWithColor, free]}
							dataKey="utilizationPercentage"
							nameKey="name"
							innerRadius={60}
							strokeWidth={5}
						>
							<Label
								content={({ viewBox }) => {
									if (viewBox && "cx" in viewBox && "cy" in viewBox) {
										return (
											<text x={viewBox.cx} y={viewBox.cy} textAnchor="middle" dominantBaseline="middle">
												<tspan x={viewBox.cx} y={viewBox.cy} className="fill-foreground text-3xl font-bold">
													{(totalUtilization * 100).toFixed(2)}%
												</tspan>
												<tspan x={viewBox.cx} y={(viewBox.cy || 0) + 24} className="fill-muted-foreground">
													Gesamt-Nutzung
												</tspan>
											</text>
										);
									}
								}}
							/>
						</Pie>
					</PieChart>
				</ChartContainer>
			</CardContent>
			<CardFooter className="flex-col gap-2 text-sm">
				<div className="flex items-center gap-2 font-medium leading-none">
					Übersicht der Nutzung <TrendingUp className="h-4 w-4" />
				</div>
				<div className="leading-none text-muted-foreground">Aktuelle Auslastung des Druckers</div>
			</CardFooter>
		</Card>
	);
}
