import { Calendar } from "lucide-react";
import Link from "next/link";
import { redirect } from "next/navigation";
import { getTopups } from "@/actions/payment";
import {
	Table,
	TableBody,
	TableCaption,
	TableCell,
	TableFooter,
	TableHead,
	TableHeader,
	TableRow,
} from "@/components/ui/table";
import type { Topup } from "@/lib/backend-types";
import { cn } from "@/lib/utils";
import { tryCatch } from "@/utils/tryCatch";
import Pagination from "./pagination";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";

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

	// Build params object
	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);
		}
	}

	const [error, topups] = await tryCatch(getTopups(apiParams));

	if (error) {
		if (error.message.includes("Unauthorized")) {
			redirect("/auth/signin");
		} else {
			return <pre>{JSON.stringify(error, null, 2)}</pre>;
		}
	}
	const { data, meta } = topups;
	return (
		<div>
			{data?.length === 0 ? (
				<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
					<h3>No topups yet.</h3>
				</div>
			) : (
				<>
					<div className="hidden sm:block">
						<Table className="overflow-scroll">
							<TableCaption>Table of all topups.</TableCaption>
							<TableHeader>
								<TableRow>
									<TableHead>Details</TableHead>
									<TableHead>Status</TableHead>
									<TableHead>Amount</TableHead>
								</TableRow>
							</TableHeader>
							<TableBody className="overflow-scroll">
								{topups?.data?.map((topup) => (
									<TableRow key={topup.id}>
										<TableCell>
											<div
												className={cn(
													"flex flex-col items-start border rounded p-2",
													topup?.paid
														? "bg-green-500/10 border-dashed border-green-500"
														: topup?.is_expired
															? "bg-gray-500/10 border-dashed border-gray-500 dark:border-gray-500/50"
															: "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50",
												)}
											>
												<div className="flex items-center gap-2">
													<Calendar size={16} opacity={0.5} />
													<span className="text-muted-foreground">
														{new Date(topup.created_at).toLocaleDateString(
															"en-US",
															{
																month: "short",
																day: "2-digit",
																year: "numeric",
																minute: "2-digit",
																hour: "2-digit",
															},
														)}
													</span>
												</div>

												<div className="flex items-center gap-2 mt-2">
													<Link
														className="font-medium hover:underline"
														href={`/top-ups/${topup.id}`}
													>
														<Button size={"sm"} variant="outline">
															View Details
														</Button>
													</Link>
													{!topup.is_expired && (

														<Badge
															className={cn(
																topup?.paid
																	? "text-green-500 bg-green-500/20"
																	: "text-yellow-500 bg-yellow-500/20",
															)}
															variant={topup.paid ? "outline" : "secondary"}
														>
															{topup.paid ? "Paid" : "Unpaid"}
														</Badge>
													)}
												</div>
											</div>
										</TableCell>

										<TableCell>
											<span className="font-semibold pr-2">
												{topup.paid ? (
													<Badge className="bg-green-100 dark:bg-green-700" variant="outline">{topup.status}</Badge>
												) : topup.is_expired ? (
													<Badge>Expired</Badge>
												) : (
													<Badge variant="outline">{topup.status}</Badge>
												)}
											</span>
										</TableCell>
										<TableCell>
											<span className="font-semibold pr-2">
												{topup.amount.toFixed(2)}
											</span>
											MVR
										</TableCell>
									</TableRow>
								))}
							</TableBody>
							<TableFooter>
								<TableRow>
									<TableCell colSpan={4} className="text-muted-foreground">
										{meta?.total === 1 ? (
											<p className="text-center">
												Total {meta?.total} topup.
											</p>
										) : (
											<p className="text-center">
												Total {meta?.total} topups.
											</p>
										)}
									</TableCell>
								</TableRow>
							</TableFooter>
						</Table>

					</div>
					<div className="sm:hidden block">
						{data.map((topup) => (
							<MobileTopupDetails key={topup.id} topup={topup} />
						))}
					</div>
					<Pagination
						totalPages={meta.total / meta.per_page}
						currentPage={meta.current_page}
					/>
				</>
			)}
		</div>
	);
}

function MobileTopupDetails({ topup }: { topup: Topup }) {
	return (
		<div
			className={cn(
				"flex flex-col items-start border rounded p-2 my-2",
				topup?.paid
					? "bg-green-500/10 border-dashed border-green=500"
					: "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50",
			)}
		>
			<div className="flex items-center gap-2">
				<Calendar size={16} opacity={0.5} />
				<span className="text-muted-foreground text-sm">
					{new Date(topup.created_at).toLocaleDateString("en-US", {
						month: "short",
						day: "2-digit",
						year: "numeric",
					})}
				</span>
			</div>

			<div className="flex items-center gap-2 mt-2">
				<Link
					className="font-medium hover:underline"
					href={`/top-ups/${topup.id}`}
				>
					<Button size={"sm"} variant="outline">
						View Details
					</Button>
				</Link>
				<Badge
					className={cn(
						topup?.paid
							? "text-green-500 bg-green-500/20"
							: "text-yellow-500 bg-yellow-500/20",
					)}
					variant={topup.paid ? "outline" : "secondary"}
				>
					{topup.paid ? "Paid" : "Unpaid"}
				</Badge>
			</div>
			<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border">
				<div className="block sm:hidden">
					<h3 className="text-sm font-medium">Amount</h3>
					<span className="text-sm text-muted-foreground">
						{topup.amount.toFixed(2)} MVR
					</span>
				</div>
			</div>
		</div>
	);
}
