"use client";

import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { type ChartConfig, ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart";
import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";

export const description = "Ein Bereichsdiagramm zur Darstellung der prognostizierten Nutzung pro Wochentag";

interface ForecastData {
	day: number; // 0 for Sunday, 1 for Monday, ..., 6 for Saturday
	usageMinutes: number;
}

interface ForecastChartProps {
	forecastData: ForecastData[];
}

const chartConfig = {
	usage: {
		label: "Prognostizierte Nutzung",
		color: "hsl(var(--chart-1))",
	},
} satisfies ChartConfig;

const daysOfWeek = ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"];

export function ForecastPrinterUsageChart({ forecastData }: ForecastChartProps) {
	// Transform and slice data to fit the chart structure
	const chartData = forecastData.map((data) => ({
		//slice(1, forecastData.length - 1).
		day: daysOfWeek[data.day], // Map day number to weekday name
		usage: data.usageMinutes,
	}));

	return (
		<Card>
			<CardHeader>
				<CardTitle>Prognostizierte Nutzung pro Wochentag</CardTitle>
			</CardHeader>
			<CardContent>
				<ChartContainer className="h-64 w-full" config={chartConfig}>
					<AreaChart accessibilityLayer data={chartData} margin={{ left: 12, right: 12, top: 12 }}>
						<CartesianGrid vertical={true} />
						<XAxis dataKey="day" type="category" tickLine={true} tickMargin={10} axisLine={false} />
						<YAxis type="number" dataKey="usage" tickLine={false} tickMargin={10} axisLine={false} />
						<ChartTooltip cursor={false} content={<ChartTooltipContent hideLabel />} />
						<Area
							dataKey="usage"
							type="step"
							fill="hsl(var(--chart-1))"
							fillOpacity={0.4}
							stroke="hsl(var(--chart-1))"
						/>
					</AreaChart>
				</ChartContainer>
			</CardContent>
			<CardFooter className="flex-col items-start gap-2 text-sm">
				<div className="flex items-center gap-2 font-medium leading-none">
					Zeigt die prognostizierte Nutzungszeit pro Wochentag in Minuten.
				</div>
				<div className="leading-none text-muted-foreground">
					Besten Tage zur Wartung: {bestMaintenanceDays(forecastData)}
				</div>
			</CardFooter>
		</Card>
	);
}

function bestMaintenanceDays(forecastData: ForecastData[]) {
	const sortedData = forecastData.map((a) => a).sort((a, b) => a.usageMinutes - b.usageMinutes); // Sort ascending

	const q1Index = Math.floor(sortedData.length * 0.33);
	const q1 = sortedData[q1Index].usageMinutes; // First quartile (Q1) value

	const filteredData = sortedData.filter((data) => data.usageMinutes <= q1);

	return filteredData
		.map((data) => {
			const days = ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"];
			return days[data.day];
		})
		.join(", ");
}
