import { AbortReasonCountChart } from "@/app/admin/charts/printer-error-chart";
import { PrinterErrorRateChart } from "@/app/admin/charts/printer-error-rate";
import { ForecastPrinterUsageChart } from "@/app/admin/charts/printer-forecast";
import { PrinterUtilizationChart } from "@/app/admin/charts/printer-utilization";
import { PrinterVolumeChart } from "@/app/admin/charts/printer-volume";
import { DataCard } from "@/components/data-card";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { db } from "@/server/db";
import { calculatePrinterErrorRate } from "@/utils/analytics/error-rate";
import { calculateAbortReasonsCount } from "@/utils/analytics/errors";
import { forecastPrinterUsage } from "@/utils/analytics/forecast";
import { calculatePrinterUtilization } from "@/utils/analytics/utilization";
import { calculatePrintVolumes } from "@/utils/analytics/volume";
import type { Metadata } from "next";

export const metadata: Metadata = {
	title: "Admin Dashboard",
};

export const dynamic = "force-dynamic";

export default async function AdminPage() {
	const currentDate = new Date();

	const lastMonth = new Date();
	lastMonth.setDate(currentDate.getDate() - 31);
	const printers = await db.query.printers.findMany({});
	const printJobs = await db.query.printJobs.findMany({
		where: (job, { gte }) => gte(job.startAt, lastMonth),
		with: {
			printer: true,
		},
	});
	if (printJobs.length < 1) {
		return (
			<Card className="w-full">
				<CardHeader>
					<CardTitle>Druckaufträge</CardTitle>
					<CardDescription>Zurzeit sind keine Druckaufträge verfügbar.</CardDescription>
				</CardHeader>
				<CardContent>
					<p>Aktualisieren Sie die Seite oder prüfen Sie später erneut, ob neue Druckaufträge verfügbar sind.</p>
				</CardContent>
			</Card>
		);
	}

	const currentPrintJobs = printJobs.filter((job) => {
		if (job.aborted) return false;

		const endAt = job.startAt.getTime() + job.durationInMinutes * 1000 * 60;

		return endAt > currentDate.getTime();
	});
	const occupiedPrinters = currentPrintJobs.map((job) => job.printer.id);
	const freePrinters = printers.filter((printer) => !occupiedPrinters.includes(printer.id));
	const printerUtilization = calculatePrinterUtilization(printJobs);
	const printerVolume = calculatePrintVolumes(printJobs);
	const printerAbortReasons = calculateAbortReasonsCount(printJobs);
	const printerErrorRate = calculatePrinterErrorRate(printJobs);
	const printerForecast = forecastPrinterUsage(printJobs);

	return (
		<>
			<Tabs defaultValue={"@general"} className="flex flex-col gap-4 items-start">
				<TabsList className="bg-neutral-100 w-full py-6">
					<TabsTrigger value="@general">Allgemein</TabsTrigger>
					<TabsTrigger value="@capacity">Druckerauslastung</TabsTrigger>
					<TabsTrigger value="@report">Fehlerberichte</TabsTrigger>
					<TabsTrigger value="@forecasts">Prognosen</TabsTrigger>
				</TabsList>
				<TabsContent value="@general" className="w-full">
					<div className="flex flex-col lg:grid lg:grid-cols-2 gap-4">
						<div className="w-full col-span-2">
							<DataCard
								title="Aktuelle Auslastung"
								value={`${Math.round((occupiedPrinters.length / (freePrinters.length + occupiedPrinters.length)) * 100)}%`}
								icon={"Percent"}
							/>
						</div>
						<DataCard title="Aktive Drucker" value={occupiedPrinters.length} icon={"Rotate3d"} />
						<DataCard title="Freie Drucker" value={freePrinters.length} icon={"PowerOff"} />
					</div>
				</TabsContent>
				<TabsContent value="@capacity" className="w-full">
					<div className="flex flex-col lg:grid lg:grid-cols-2 gap-4">
						<div className="w-full col-span-2">
							<PrinterVolumeChart printerVolume={printerVolume} />
						</div>
						{printerUtilization.map((data) => (
							<PrinterUtilizationChart key={data.printerId} data={data} />
						))}
					</div>
				</TabsContent>
				<TabsContent value="@report" className="w-full">
					<div className="flex flex-col lg:grid lg:grid-cols-2 gap-4">
						<div className="w-full col-span-2">
							<PrinterErrorRateChart printerErrorRate={printerErrorRate} />
						</div>
						<div className="w-full col-span-2">
							<AbortReasonCountChart abortReasonCount={printerAbortReasons} />
						</div>
					</div>
				</TabsContent>
				<TabsContent value="@forecasts" className="w-full">
					<div className="flex flex-col lg:grid lg:grid-cols-2 gap-4">
						<div className="w-full col-span-2">
							<ForecastPrinterUsageChart
								forecastData={printerForecast.map((usageMinutes, index) => ({
									day: index,
									usageMinutes,
								}))}
							/>
						</div>
					</div>
				</TabsContent>
			</Tabs>
		</>
	);
}
