import { columns } from "@/app/my/jobs/columns";
import { JobsTable } from "@/app/my/jobs/data-table";
import { DynamicPrinterCards } from "@/components/dynamic-printer-cards";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { validateRequest } from "@/server/auth";
import { db } from "@/server/db";
import { printJobs } from "@/server/db/schema";
import { desc, eq } from "drizzle-orm";
import type { Metadata } from "next";

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

export default async function HomePage() {
	const { user } = await validateRequest();
	const userIsLoggedIn = Boolean(user);

	const printers = await db.query.printers.findMany({
		with: {
			printJobs: {
				limit: 1,
				orderBy: (printJobs, { desc }) => [desc(printJobs.startAt)],
			},
		},
	});

	// biome-ignore lint/suspicious/noExplicitAny: temp. fix for jobs
	let jobs: any[] = [];
	if (userIsLoggedIn) {
		jobs = await db.query.printJobs.findMany({
			// biome-ignore lint/style/noNonNullAssertion: User exists if userIsLoggedIn is true
			where: eq(printJobs.userId, user!.id),
			orderBy: [desc(printJobs.startAt)],
			with: {
				printer: true,
			},
		});
	}

	return (
		<>
			{/* NEEDS TO BE FIXED FOR A NEW / EMPTY USER {isLoggedIn && <PersonalizedCards />} */}
			<Card>
				<CardHeader>
					<CardTitle>Druckerbelegung</CardTitle>
					<CardDescription>({printers.length} Verfügbar)</CardDescription>
				</CardHeader>
				<CardContent className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
					<DynamicPrinterCards user={user} />
				</CardContent>
			</Card>
			{userIsLoggedIn && (
				<Card>
					<CardHeader>
						<CardTitle>Druckaufträge</CardTitle>
						<CardDescription>Deine aktuellen Druckaufträge</CardDescription>
					</CardHeader>
					<CardContent>
						<JobsTable columns={columns} data={jobs} />
					</CardContent>
				</Card>
			)}
		</>
	);
}
