import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { formatCents } from "@/lib/drinkkaart";
import { orpc } from "@/utils/orpc";
import { ReverseDialog } from "./ReverseDialog";

interface TransactionRow {
	id: string;
	type: "deduction" | "reversal";
	userId: string;
	userName: string;
	userEmail: string;
	adminId: string;
	adminName: string;
	amountCents: number;
	balanceBefore: number;
	balanceAfter: number;
	note: string | null;
	reversedBy: string | null;
	reverses: string | null;
	createdAt: Date;
}

export function AdminTransactionLog() {
	const [page, setPage] = useState(1);
	const [reverseTarget, setReverseTarget] = useState<TransactionRow | null>(
		null,
	);

	const { data, isLoading, refetch } = useQuery({
		...orpc.drinkkaart.getTransactionLog.queryOptions({
			input: { page, pageSize: 50 },
		}),
		refetchInterval: 30_000,
	});

	const transactions = (data?.transactions ?? []) as TransactionRow[];
	const total = data?.total ?? 0;
	const totalPages = Math.ceil(total / 50);

	if (isLoading) {
		return <p className="text-sm text-white/40">Laden...</p>;
	}

	if (transactions.length === 0) {
		return <p className="text-sm text-white/40">Geen transacties gevonden.</p>;
	}

	return (
		<div>
			<div className="mb-3 flex items-center justify-between">
				<p className="text-sm text-white/50">{total} transacties</p>
				<Button
					onClick={() => refetch()}
					size="sm"
					variant="outline"
					className="border-white/20 bg-transparent text-sm text-white hover:bg-white/10"
				>
					Vernieuwen
				</Button>
			</div>

			<div className="overflow-x-auto rounded-xl border border-white/10">
				<table className="w-full text-sm">
					<thead>
						<tr className="border-white/10 border-b bg-white/5">
							<th className="px-4 py-3 text-left font-medium text-white/50">
								Tijdstip
							</th>
							<th className="px-4 py-3 text-left font-medium text-white/50">
								Gebruiker
							</th>
							<th className="px-4 py-3 text-left font-medium text-white/50">
								Bedrag
							</th>
							<th className="px-4 py-3 text-left font-medium text-white/50">
								Type
							</th>
							<th className="px-4 py-3 text-left font-medium text-white/50">
								Admin
							</th>
							<th className="px-4 py-3 text-left font-medium text-white/50">
								Opmerking
							</th>
							<th className="px-4 py-3 text-left font-medium text-white/50">
								Actie
							</th>
						</tr>
					</thead>
					<tbody>
						{transactions.map((t) => {
							const date = new Date(t.createdAt).toLocaleString("nl-BE", {
								day: "2-digit",
								month: "2-digit",
								hour: "2-digit",
								minute: "2-digit",
							});
							const isReversal = t.type === "reversal";
							const canReverse = t.type === "deduction" && !t.reversedBy;

							return (
								<tr
									key={t.id}
									className={`border-white/5 border-b ${isReversal ? "bg-green-400/5" : ""}`}
								>
									<td className="px-4 py-3 text-white/60 tabular-nums">
										{date}
									</td>
									<td className="px-4 py-3">
										<p className="font-medium text-white">{t.userName}</p>
										<p className="text-white/40 text-xs">{t.userEmail}</p>
									</td>
									<td className="px-4 py-3">
										<span
											className={`font-medium ${isReversal ? "text-green-400" : "text-red-400"}`}
										>
											{isReversal ? "+ " : "− "}
											{formatCents(t.amountCents)}
										</span>
									</td>
									<td className="px-4 py-3">
										{isReversal ? (
											<span className="rounded-full border border-green-400/30 bg-green-400/10 px-2 py-0.5 text-green-300 text-xs">
												↩ Teruggedraaid
											</span>
										) : t.reversedBy ? (
											<span className="rounded-full border border-white/10 bg-white/5 px-2 py-0.5 text-white/40 text-xs">
												Teruggedraaid
											</span>
										) : (
											<span className="rounded-full border border-red-400/20 bg-red-400/10 px-2 py-0.5 text-red-300 text-xs">
												Afschrijving
											</span>
										)}
									</td>
									<td className="px-4 py-3 text-sm text-white/60">
										{t.adminName}
									</td>
									<td className="px-4 py-3 text-sm text-white/50">
										{t.note || "—"}
									</td>
									<td className="px-4 py-3">
										{canReverse && (
											<Button
												size="sm"
												variant="outline"
												onClick={() => setReverseTarget(t)}
												className="border-orange-400/30 bg-transparent text-orange-300 hover:bg-orange-400/10"
											>
												Draai terug
											</Button>
										)}
									</td>
								</tr>
							);
						})}
					</tbody>
				</table>
			</div>

			{/* Pagination */}
			{totalPages > 1 && (
				<div className="mt-4 flex items-center justify-center gap-3">
					<Button
						onClick={() => setPage((p) => Math.max(1, p - 1))}
						disabled={page === 1}
						variant="outline"
						size="sm"
						className="border-white/20 bg-transparent text-white hover:bg-white/10 disabled:opacity-50"
					>
						Vorige
					</Button>
					<span className="text-sm text-white/60">
						{page} / {totalPages}
					</span>
					<Button
						onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
						disabled={page === totalPages}
						variant="outline"
						size="sm"
						className="border-white/20 bg-transparent text-white hover:bg-white/10 disabled:opacity-50"
					>
						Volgende
					</Button>
				</div>
			)}

			{reverseTarget && (
				<ReverseDialog
					transaction={reverseTarget}
					onClose={() => setReverseTarget(null)}
				/>
			)}
		</div>
	);
}
