"use client";

import { PrinterCard } from "@/components/printer-card";
import { Skeleton } from "@/components/ui/skeleton";
import type { InferResultType } from "@/utils/drizzle";
import { fetcher } from "@/utils/fetch";
import type { RegisteredDatabaseUserAttributes } from "lucia";
import useSWR from "swr";

interface DynamicPrinterCardsProps {
	user: RegisteredDatabaseUserAttributes | null;
}

export function DynamicPrinterCards(props: DynamicPrinterCardsProps) {
	const { user } = props;
	const { data, error, isLoading } = useSWR("/api/printers", fetcher, {
		refreshInterval: 1000 * 15,
	});

	if (error) {
		return <div>Ein Fehler ist aufgetreten.</div>;
	}

	if (isLoading) {
		return (
			<>
				{new Array(6).fill(null).map((_, index) => (
					// biome-ignore lint/suspicious/noArrayIndexKey: <explanation>
					<Skeleton key={index} className="w-auto h-36 animate-pulse" />
				))}
			</>
		);
	}

	return data.map((printer: InferResultType<"printers", { printJobs: true }>) => {
		return <PrinterCard key={printer.id} printer={printer} user={user} />;
	});
}
