import { authOptions } from "@/app/auth";
import {
	Table,
	TableBody,
	TableCaption,
	TableCell,
	TableFooter,
	TableHead,
	TableHeader,
	TableRow,
} from "@/components/ui/table";
import { getDevices } from "@/queries/devices";
import { tryCatch } from "@/utils/tryCatch";
import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";
import ClickableRow from "./clickable-row";
import ClientErrorMessage from "./client-error-message";
import DeviceCard from "./device-card";
import Pagination from "./pagination";

export async function DevicesTable({
	searchParams,
	parentalControl,
}: {
	searchParams: Promise<{
		query: string;
		page: number;
	}>;
	parentalControl?: boolean;
}) {
	const session = await getServerSession(authOptions);
	const isAdmin = session?.user?.is_superuser;
	const query = (await searchParams)?.query || "";
	const page = (await searchParams)?.page || 1;

	const limit = 10; // Items per page
	const offset = (page - 1) * limit; // Calculate offset based on page

	const [error, devices] = await tryCatch(
		getDevices({ query: query, limit: limit, offset: offset }),
	);
	if (error) {
		if (error.message === "UNAUTHORIZED") {
			redirect("/auth/signin");
		} else {
			return <ClientErrorMessage message={error.message} />;
		}
	}
	const { meta, data } = devices;
	return (
		<div>
			{data?.length === 0 ? (
				<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
					<h3>No devices yet.</h3>
				</div>
			) : (
				<>
					<div className="hidden sm:block">
						<Table className="overflow-scroll">
							<TableCaption>Table of all devices.</TableCaption>
							<TableHeader>
								<TableRow>
									<TableHead>Device Name</TableHead>
									<TableHead>MAC Address</TableHead>
									<TableHead>#</TableHead>
								</TableRow>
							</TableHeader>
							<TableBody className="overflow-scroll">
								{data?.map((device) => (
									<ClickableRow
										admin={isAdmin}
										key={device.id}
										device={device}
										parentalControl={parentalControl}
									/>
								))}
							</TableBody>
							<TableFooter>
								<TableRow>
									<TableCell colSpan={2}>
										{query?.length > 0 && (
											<p className="text-sm text-muted-foreground">
												Showing {meta?.total} devices for &quot;{query}
												&quot;
											</p>
										)}
									</TableCell>
									<TableCell className="text-muted-foreground">
										{meta?.total} devices
									</TableCell>
								</TableRow>
							</TableFooter>
						</Table>
					</div>
					<div className="sm:hidden my-4">
						{data?.map((device) => (
							<DeviceCard
								parentalControl={parentalControl}
								key={device.id}
								device={device}
							/>
						))}
					</div>
					<Pagination
						totalPages={meta?.last_page}
						currentPage={meta?.current_page}
					/>
				</>
			)}
		</div>
	);
}
