import { useQuery, useQueryClient } from "@tanstack/react-query";
import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import {
	Calendar,
	CreditCard,
	Music,
	QrCode,
	Users,
	Wallet,
} from "lucide-react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { QrCodeDisplay } from "@/components/drinkkaart/QrCodeDisplay";
import { TopUpHistory } from "@/components/drinkkaart/TopUpHistory";
import { TopUpModal } from "@/components/drinkkaart/TopUpModal";
import { TransactionHistory } from "@/components/drinkkaart/TransactionHistory";
import { authClient } from "@/lib/auth-client";
import { formatCents } from "@/lib/drinkkaart";
import { client, orpc } from "@/utils/orpc";

interface AccountSearch {
	topup?: string;
	welkom?: string;
}

export const Route = createFileRoute("/account")({
	validateSearch: (search: Record<string, unknown>): AccountSearch => ({
		topup: typeof search.topup === "string" ? search.topup : undefined,
		welkom: typeof search.welkom === "string" ? search.welkom : undefined,
	}),
	component: AccountPage,
});

function PaymentBadge({ status }: { status: string | null }) {
	if (status === "paid") {
		return (
			<span className="inline-flex items-center gap-1 rounded-full bg-green-500/20 px-2 py-0.5 font-medium text-green-300 text-xs">
				<svg
					className="h-3 w-3"
					fill="none"
					viewBox="0 0 24 24"
					stroke="currentColor"
					strokeWidth={2.5}
					aria-hidden="true"
				>
					<path
						strokeLinecap="round"
						strokeLinejoin="round"
						d="M5 13l4 4L19 7"
					/>
				</svg>
				Betaald
			</span>
		);
	}
	if (status === "extra_payment_pending") {
		return (
			<span className="inline-flex items-center gap-1 rounded-full bg-yellow-500/20 px-2 py-0.5 font-medium text-xs text-yellow-300">
				Extra betaling verwacht
			</span>
		);
	}
	return (
		<span className="inline-flex items-center gap-1 rounded-full bg-orange-500/20 px-2 py-0.5 font-medium text-orange-300 text-xs">
			In behandeling
		</span>
	);
}

function AccountPage() {
	const navigate = useNavigate();
	const queryClient = useQueryClient();
	const search = Route.useSearch();
	const [showQr, setShowQr] = useState(false);
	const [showTopUp, setShowTopUp] = useState(false);

	const sessionQuery = useQuery({
		queryKey: ["session"],
		queryFn: () => authClient.getSession(),
	});

	// Client-side auth check: redirect to login if not authenticated
	useEffect(() => {
		if (!sessionQuery.isLoading && !sessionQuery.data?.data?.user) {
			navigate({ to: "/login" });
		}
	}, [sessionQuery.isLoading, sessionQuery.data, navigate]);

	const drinkkaartQuery = useQuery(
		orpc.drinkkaart.getMyDrinkkaart.queryOptions(),
	);

	const registrationQuery = useQuery(orpc.getMyRegistrations.queryOptions());

	// Handle topup=success redirect (from Lemon Squeezy returning to /account)
	useEffect(() => {
		if (search.topup === "success") {
			toast.success("Oplading geslaagd! Je saldo is bijgewerkt.");
			queryClient.invalidateQueries({
				queryKey: orpc.drinkkaart.getMyDrinkkaart.key(),
			});
			const url = new URL(window.location.href);
			url.searchParams.delete("topup");
			window.history.replaceState({}, "", url.toString());
		}
	}, [search.topup, queryClient]);

	// Silent background call to claim any pending registration fee credit.
	// This catches cases where: webhook didn't fire/failed, or user signed up after paying.
	// No UI feedback needed — if there's nothing to claim, it does nothing.
	useEffect(() => {
		client.claimRegistrationCredit().catch((err) => {
			console.error("claimRegistrationCredit failed:", err);
		});
	}, []);

	// Welcome toast after fresh signup
	useEffect(() => {
		if (search.welkom === "1") {
			toast.success("Welkom! Je account is aangemaakt.");
			const url = new URL(window.location.href);
			url.searchParams.delete("welkom");
			window.history.replaceState({}, "", url.toString());
		}
	}, [search.welkom]);

	const user = sessionQuery.data?.data?.user as
		| { name?: string; email?: string }
		| undefined;

	const registrations = registrationQuery.data ?? [];
	const drinkkaart = drinkkaartQuery.data;

	const isLoading =
		sessionQuery.isLoading ||
		drinkkaartQuery.isLoading ||
		registrationQuery.isLoading;

	if (isLoading) {
		return (
			<div className="flex min-h-screen items-center justify-center bg-[#214e51]">
				<div className="h-10 w-10 animate-spin rounded-full border-2 border-white/20 border-t-white" />
			</div>
		);
	}

	return (
		<div>
			<main className="mx-auto max-w-5xl px-4 py-12">
				{/* Page header */}
				<div className="mb-8">
					<h1 className="mb-1 font-['Intro',sans-serif] text-4xl text-white">
						Mijn Account
					</h1>
					<p className="text-white/50">
						{user?.name && (
							<span className="mr-2 font-medium text-white/70">
								{user.name}
							</span>
						)}
						{user?.email}
					</p>
				</div>

				<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
					{/* ── Left column: Registration ── */}
					<section>
						<h2 className="mb-3 flex items-center gap-2 font-['Intro',sans-serif] text-lg text-white/80">
							<Calendar className="h-4 w-4 shrink-0 text-white/40" />
							Mijn Inschrijving
						</h2>

						{registrations.length > 0 ? (
							<div className="flex flex-col gap-4">
								{registrations.map((registration) => (
									<div
										key={registration.id}
										className="rounded-2xl border border-white/10 bg-white/5 p-6"
									>
										{/* Type badge */}
										<div className="mb-4 flex items-center justify-between">
											<div className="flex items-center gap-2">
												{registration.registrationType === "performer" ? (
													<span className="inline-flex items-center gap-1.5 rounded-full bg-amber-500/20 px-3 py-1 font-medium text-amber-300 text-sm">
														<Music className="h-3.5 w-3.5" />
														Artiest
													</span>
												) : (
													<span className="inline-flex items-center gap-1.5 rounded-full bg-teal-500/20 px-3 py-1 font-medium text-sm text-teal-300">
														<Users className="h-3.5 w-3.5" />
														Bezoeker
													</span>
												)}
											</div>
											{(registration.registrationType !== "performer" ||
												(registration.giftAmount ?? 0) > 0) && (
												<PaymentBadge status={registration.paymentStatus} />
											)}
										</div>

										{/* Name */}
										<p className="mb-1 font-medium text-lg text-white">
											{registration.firstName} {registration.lastName}
										</p>

										{/* Art form (performer only) */}
										{registration.registrationType === "performer" &&
											registration.artForm && (
												<p className="mb-1 text-sm text-white/60">
													Kunstvorm:{" "}
													<span className="text-white/80">
														{registration.artForm}
													</span>
												</p>
											)}

										{/* Guests (watcher only) */}
										{registration.registrationType === "watcher" &&
											registration.guests.length > 0 && (
												<p className="mb-1 text-sm text-white/60">
													{registration.guests.length + 1} personen (jij +{" "}
													{registration.guests.length} gast
													{registration.guests.length > 1 ? "en" : ""})
												</p>
											)}

										{/* Drink card value */}
										{registration.registrationType === "watcher" &&
											(registration.drinkCardValue ?? 0) > 0 && (
												<p className="mb-1 text-sm text-white/60">
													Drinkkaart:{" "}
													<span className="text-white/80">
														€{registration.drinkCardValue}
													</span>
												</p>
											)}

										{/* Gift */}
										{(registration.giftAmount ?? 0) > 0 && (
											<p className="mb-1 text-sm text-white/60">
												Gift:{" "}
												<span className="text-white/80">
													€{(registration.giftAmount ?? 0) / 100}
												</span>
											</p>
										)}

										{/* Date */}
										<p className="mt-3 text-white/40 text-xs">
											Ingeschreven op{" "}
											{new Date(registration.createdAt).toLocaleDateString(
												"nl-BE",
												{
													day: "numeric",
													month: "long",
													year: "numeric",
												},
											)}
										</p>

										{/* Action */}
										{registration.managementToken && (
											<div className="mt-5">
												<Link
													to="/manage/$token"
													params={{ token: registration.managementToken }}
													className="inline-flex items-center gap-2 rounded-lg bg-white/10 px-4 py-2 text-sm text-white transition-colors hover:bg-white/20"
												>
													Beheer inschrijving
													<svg
														className="h-3.5 w-3.5"
														fill="none"
														viewBox="0 0 24 24"
														stroke="currentColor"
														strokeWidth={2}
														aria-hidden="true"
													>
														<path
															strokeLinecap="round"
															strokeLinejoin="round"
															d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3"
														/>
													</svg>
												</Link>
											</div>
										)}
									</div>
								))}
							</div>
						) : (
							<div className="rounded-2xl border border-white/10 bg-white/5 p-6">
								<p className="mb-3 text-sm text-white/60">
									We vonden geen actieve inschrijving voor dit e-mailadres.
								</p>
								<a
									href="/#registration"
									className="inline-flex items-center gap-2 rounded-lg bg-white/10 px-4 py-2 text-sm text-white transition-colors hover:bg-white/20"
								>
									Inschrijven voor het evenement
									<svg
										className="h-3.5 w-3.5"
										fill="none"
										viewBox="0 0 24 24"
										stroke="currentColor"
										strokeWidth={2}
										aria-hidden="true"
									>
										<path
											strokeLinecap="round"
											strokeLinejoin="round"
											d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3"
										/>
									</svg>
								</a>
							</div>
						)}
					</section>

					{/* ── Right column: Drinkkaart ── */}
					<section>
						<h2 className="mb-3 flex items-center gap-2 font-['Intro',sans-serif] text-lg text-white/80">
							<CreditCard className="h-4 w-4 shrink-0 text-white/40" />
							Mijn Drinkkaart
						</h2>

						{/* Balance card */}
						<div className="mb-4 rounded-2xl border border-white/10 bg-white/5 p-6">
							<p className="mb-1 text-sm text-white/50">Huidig saldo</p>
							<p className="mb-4 font-['Intro',sans-serif] text-5xl text-white">
								{drinkkaart ? formatCents(drinkkaart.balance) : "—"}
							</p>

							<div className="flex flex-wrap gap-3">
								<button
									type="button"
									onClick={() => setShowQr((v) => !v)}
									className="inline-flex items-center gap-2 rounded-lg border border-white/30 bg-transparent px-4 py-2 text-sm text-white transition-colors hover:bg-white/10"
								>
									<QrCode className="h-4 w-4" />
									{showQr ? "Verberg QR-code" : "Toon QR-code"}
								</button>
								<button
									type="button"
									onClick={() => setShowTopUp(true)}
									className="inline-flex items-center gap-2 rounded-lg bg-white px-4 py-2 font-semibold text-[#214e51] text-sm transition-colors hover:bg-white/90"
								>
									<Wallet className="h-4 w-4" />
									Opladen
								</button>
							</div>
						</div>

						{/* QR code */}
						{showQr && (
							<div className="mb-4 flex justify-center rounded-2xl border border-white/10 bg-white/5 p-6">
								<QrCodeDisplay />
							</div>
						)}

						{/* Top-up history */}
						<section className="mb-6">
							<h3 className="mb-2 font-medium text-sm text-white/50 uppercase tracking-wider">
								Opladingen
							</h3>
							{drinkkaart ? (
								<TopUpHistory
									topups={
										drinkkaart.topups as Parameters<
											typeof TopUpHistory
										>[0]["topups"]
									}
								/>
							) : (
								<p className="text-sm text-white/40">Laden...</p>
							)}
						</section>

						{/* Transaction history */}
						<section>
							<h3 className="mb-2 font-medium text-sm text-white/50 uppercase tracking-wider">
								Transacties
							</h3>
							{drinkkaart ? (
								<TransactionHistory
									transactions={
										drinkkaart.transactions as Parameters<
											typeof TransactionHistory
										>[0]["transactions"]
									}
								/>
							) : (
								<p className="text-sm text-white/40">Laden...</p>
							)}
						</section>
					</section>
				</div>
			</main>

			{showTopUp && <TopUpModal onClose={() => setShowTopUp(false)} />}
		</div>
	);
}
