import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
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 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,
	additionalFilters = {},

}: {
	searchParams: Promise<{
		[key: string]: unknown;
	}>;
	parentalControl?: boolean;
	additionalFilters?: Record<string, string | number | boolean>;
}) {
	const resolvedParams = await searchParams;
	const session = await getServerSession(authOptions);
	const isAdmin = session?.user?.is_admin;

	const page = Number.parseInt(resolvedParams.page as string) || 1;
	const limit = 10;
	const offset = (page - 1) * limit;

	// Build params object for getDevices
	const apiParams: Record<string, string | number | undefined> = {};
	for (const [key, value] of Object.entries(resolvedParams)) {
		if (value !== undefined && value !== "") {
			apiParams[key] = typeof value === "number" ? value : String(value);
		}
	}

	for (const [key, value] of Object.entries(additionalFilters)) {
		if (value !== undefined && value !== "") {
			apiParams[key] = typeof value === "number" ? value : String(value);
		}
	}
	apiParams.limit = limit;
	apiParams.offset = offset;
	console.log("API Params:", apiParams);
	const [error, devices] = await tryCatch(
		getDevices(apiParams),
	);
	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)] text-muted-foreground flex flex-col items-center justify-center my-4">
					<h3>No devices.</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>Vendor</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={4} className="text-muted-foreground">
										{meta?.total === 1 ? (
											<p className="text-center">
												Total {meta?.total} device.
											</p>
										) : (
											<p className="text-center">
												Total {meta?.total} devices.
											</p>
										)}
									</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 >
	);
}
