import Link from "next/link";
import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { getPayments } from "@/actions/payment";
import { authOptions } from "@/app/auth";
import Pagination from "@/components/pagination";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
	Table,
	TableBody,
	TableCaption,
	TableCell,
	TableFooter,
	TableHead,
	TableHeader,
	TableRow,
} from "@/components/ui/table";
import { tryCatch } from "@/utils/tryCatch";
import ClientErrorMessage from "../client-error-message";

export async function UsersPaymentsTable({
	searchParams,
}: {
	searchParams: Promise<{
		[key: string]: unknown;
	}>;
}) {
	const resolvedParams = await searchParams;

	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);
		}
	}
	apiParams.limit = limit;
	apiParams.offset = offset;

	const [error, payments] = await tryCatch(getPayments(apiParams, true));
	if (error) {
		if (error.message === "UNAUTHORIZED") {
			redirect("/auth/signin");
		} else {
			return <ClientErrorMessage message={error.message} />;
		}
	}
	const { meta, data } = payments;

	// return <pre>{JSON.stringify(payments, null, 2)}</pre>;
	return (
		<div>
			{data.length === 0 ? (
				<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
					<h3>No user payments yet.</h3>
				</div>
			) : (
				<>
					<Table className="overflow-scroll">
						<TableCaption>Table of all users.</TableCaption>
						<TableHeader>
							<TableRow>
								<TableHead>Devices paid</TableHead>
								<TableHead>User</TableHead>
								<TableHead>Amount</TableHead>
								<TableHead>Duration</TableHead>
								<TableHead>Payment Status</TableHead>
								<TableHead>Payment Method</TableHead>
								<TableHead>MIB Reference</TableHead>
								<TableHead>Paid At</TableHead>
								<TableHead>Action</TableHead>
							</TableRow>
						</TableHeader>
						<TableBody className="overflow-scroll">
							{data.map((payment) => (
								<TableRow
									className={`${payment.paid && "title-bg dark:bg-black"}`}
									key={payment.id}
								>
									<TableCell className="font-medium">
										<ol className="list-disc list-inside text-sm">
											{payment.devices.map((device) => (
												<li
													key={device.id}
													className="text-sm text-muted-foreground"
												>
													{device.name}
												</li>
											))}
										</ol>
									</TableCell>
									<TableCell className="font-medium">
										{/* {payment.user.id_card} */}
										<div className="flex flex-col items-start">
											{payment.devices[0]?.user?.name}
											<span className="text-muted-foreground">
												{payment.devices[0]?.user?.id_card}
											</span>
										</div>{" "}
									</TableCell>
									<TableCell>{payment.amount}</TableCell>
									<TableCell>{payment.number_of_months} Months</TableCell>

									<TableCell>
										{payment.status === "PENDING" ? (
											<Badge
												variant="outline"
												className="bg-yellow-100 text-black"
											>
												{payment.status}
											</Badge>
										) : payment.status === "PAID" ? (
											<Badge
												variant="outline"
												className="bg-lime-100 text-black"
											>
												{payment.status}
											</Badge>
										) : (
											<Badge
												variant="outline"
												className="bg-red-100 text-black"
											>
												{payment.status}
											</Badge>
										)}
									</TableCell>
									<TableCell>{payment.method}</TableCell>
									<TableCell>{payment.mib_reference}</TableCell>
									<TableCell>
										{new Date(payment.paid_at ?? "").toLocaleDateString(
											"en-US",
											{
												month: "short",
												day: "2-digit",
												year: "numeric",
												minute: "2-digit",
												hour: "2-digit",
											},
										)}
									</TableCell>

									<TableCell>
										<Link href={`/payments/${payment.id}/verify`}>
											<Button>Details</Button>
										</Link>
									</TableCell>
								</TableRow>
							))}
						</TableBody>
						<TableFooter>
							<TableRow>
								<TableCell colSpan={10} className="text-muted-foreground">
									{meta?.total === 1 ? (
										<p className="text-center">Total {meta?.total} payment.</p>
									) : (
										<p className="text-center">Total {meta?.total} payments.</p>
									)}{" "}
								</TableCell>
							</TableRow>
						</TableFooter>
					</Table>
					<Pagination
						totalPages={meta?.last_page}
						currentPage={meta?.current_page}
					/>
				</>
			)}
		</div>
	);
}
