import { Calendar } from "lucide-react";
import Link from "next/link";
import { redirect } from "next/navigation";
import { getPayments } from "@/actions/payment";
import {
	Table,
	TableBody,
	TableCaption,
	TableCell,
	TableFooter,
	TableHead,
	TableHeader,
	TableRow,
} from "@/components/ui/table";
import type { Payment } 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";
import { Separator } from "./ui/separator";

export async function PaymentsTable({
	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;
	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));

	if (error) {
		if (error.message.includes("Unauthorized")) {
			redirect("/auth/signin");
		} else {
			return <pre>{JSON.stringify(error, null, 2)}</pre>;
		}
	}
	const { data, meta } = payments;
	return (
		<div>
			{data?.length === 0 ? (
				<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
					<h3>No Payments yet.</h3>
				</div>
			) : (
				<>
					<div className="hidden sm:block">
						<Table className="overflow-scroll">
							<TableCaption>Table of all devices.</TableCaption>
							<TableHeader>
								<TableRow>
									<TableHead>Details</TableHead>
									<TableHead>Duration</TableHead>
									<TableHead>Status</TableHead>
									<TableHead>Amount</TableHead>
								</TableRow>
							</TableHeader>
							<TableBody className="overflow-scroll">
								{payments?.data?.map((payment) => (
									<TableRow key={payment.id}>
										<TableCell>
											<div
												className={cn(
													"flex flex-col items-start border rounded p-2",
													payment?.paid
														? "bg-green-500/10 border-dashed border-green-500"
														: payment?.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(payment.created_at).toLocaleDateString(
															"en-US",
															{
																month: "short",
																day: "2-digit",
																year: "numeric",
																minute: "2-digit",
																hour: "2-digit",
																timeZone: "Indian/Maldives", // Force consistent timezone
															},
														)}
													</span>
												</div>

												<div className="flex items-center gap-2 mt-2">
													<Link
														className="font-medium hover:underline"
														href={`/payments/${payment.id}`}
													>
														<Button size={"sm"} variant="outline">
															View Details
														</Button>
													</Link>
												</div>
												<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border">
													<h3 className="text-sm font-medium">Devices</h3>
													<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>
												</div>
											</div>
										</TableCell>

										<TableCell className="font-medium">
											{payment.number_of_months} Months
										</TableCell>
										<TableCell>
											<span className="font-semibold pr-2">
												{payment.paid ? (
													<Badge
														className={cn(
															payment.status === "PENDING"
																? "bg-yellow-100 text-yellow-700 dark:bg-yellow-700 dark:text-yellow-100"
																: "bg-green-100 dark:bg-green-700",
														)}
														variant="outline"
													>
														{payment.status}
													</Badge>
												) : payment.is_expired ? (
													<Badge>Expired</Badge>
												) : (
													<Badge variant="outline">{payment.status}</Badge>
												)}
											</span>
										</TableCell>
										<TableCell>
											<span className="font-semibold pr-2">
												{payment.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} 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>
					<div className="sm:hidden block">
						{data.map((payment) => (
							<MobilePaymentDetails key={payment.id} payment={payment} />
						))}
					</div>
				</>
			)}
		</div>
	);
}

export function MobilePaymentDetails({ payment, isAdmin = false }: { payment: Payment, isAdmin?: boolean }) {
	return (
		<div
			className={cn(
				"flex flex-col items-start border rounded p-2 my-2",
				payment?.paid
					? "bg-green-500/10 border-dashed border-green-500"
					: payment?.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 text-sm">
					{new Date(payment.created_at).toLocaleDateString("en-US", {
						month: "short",
						day: "2-digit",
						year: "numeric",
						minute: "2-digit",
						hour: "2-digit",
						timeZone: "Indian/Maldives", // Force consistent timezone
					})}
				</span>
			</div>

			<div className="flex items-center gap-2 mt-2">
				<Link
					className="font-medium hover:underline"
					href={`/payments/${payment.id}`}
				>
					<Button size={"sm"} variant="outline">
						View Details
					</Button>
				</Link>
			</div>
			<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border">
				<h3 className="text-sm font-medium">Devices</h3>
				<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>
				<div className="block sm:hidden">
					<Separator className="my-2" />
					<h3 className="text-sm font-medium">Duration</h3>
					<span className="text-sm text-muted-foreground">
						{payment.number_of_months} Months
					</span>
					<Separator className="my-2" />
					<h3 className="text-sm font-medium">Amount</h3>
					<div className="flex items-center justify-between">
						<span className="text-sm text-muted-foreground">
							{payment.amount.toFixed(2)} MVR
						</span>
						<span className="font-semibold pr-2">
							{payment.paid ? (
								<Badge
									className={cn(
										payment.status === "PENDING"
											? "bg-yellow-100 text-yellow-700 dark:bg-yellow-700 dark:text-yellow-100"
											: "bg-green-100 dark:bg-green-700",
									)}
									variant="outline"
								>
									{payment.status}
								</Badge>
							) : payment.is_expired ? (
								<Badge>Expired</Badge>
							) : (
								<Badge variant="secondary">{payment.status}</Badge>
							)}
						</span>
						{isAdmin && (
							<div className="my-2 text-primary flex flex-col items-start text-sm border rounded p-2 mt-2 w-full bg-white dark:bg-black">
								{payment?.user?.name}
								<span className="text-muted-foreground">{payment?.user?.id_card}</span>
							</div>
						)}
					</div>
				</div>
			</div>
		</div>
	);
}
