import { useQuery } from "@tanstack/react-query";
import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import {
	AlertCircle,
	ArrowLeft,
	ChevronLeft,
	ChevronRight,
} from "lucide-react";
import z from "zod";
import MovieCard from "@/components/nontora/MovieCard";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { parseTRPCError } from "@/lib/trpc-errors";
import { useTRPC } from "@/utils/trpc";

const LibrarySearchParamsSchema = z.object({
	page: z.coerce.number().int().positive().optional(),
});

export const Route = createFileRoute("/home/library/$id")({
	component: RouteComponent,
	validateSearch: LibrarySearchParamsSchema,
});

function RouteComponent() {
	const { id } = Route.useParams();
	const libraryId = Number.parseInt(id, 10);
	const { page = 1 } = Route.useSearch();
	const navigate = useNavigate();
	const trpc = useTRPC();

	const { data, isLoading, error } = useQuery(
		trpc.library.getTitles.queryOptions({
			libraryId,
			page,
			limit: 20,
		}),
	);

	const updatePage = (newPage: number) => {
		navigate({
			from: Route.id,
			search: (prev) => ({
				...prev,
				page: newPage === 1 ? undefined : newPage,
			}),
		});
	};

	// Loading state
	if (isLoading) {
		return (
			<div className="container mx-auto px-4 py-8">
				<Skeleton className="mb-6 h-8 w-48" />
				<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
					{Array.from(
						{ length: 12 },
						(_, i) => `skeleton-${Date.now()}-${i}`,
					).map((key) => (
						<div key={key}>
							<Skeleton className="aspect-[3/4] w-full rounded-lg" />
							<Skeleton className="mt-2 h-4 w-full" />
							<Skeleton className="mt-1 h-3 w-3/4" />
						</div>
					))}
				</div>
			</div>
		);
	}

	// Error state
	if (error) {
		const errorInfo = parseTRPCError(error);
		return (
			<div className="container mx-auto px-4 py-8">
				<Alert variant="destructive">
					<AlertCircle className="h-4 w-4" />
					<AlertTitle>{errorInfo.title}</AlertTitle>
					<AlertDescription>{errorInfo.message}</AlertDescription>
				</Alert>
				<div className="mt-6">
					<Link to="/home">
						<Button variant="outline">
							<ArrowLeft className="mr-2 h-4 w-4" />
							Back to Home
						</Button>
					</Link>
				</div>
			</div>
		);
	}

	// Empty state
	if (!data || data.titles.length === 0) {
		return (
			<div className="container mx-auto px-4 py-8">
				<h1 className="mb-6 font-bold text-2xl">Library Titles</h1>
				<Alert>
					<AlertCircle className="h-4 w-4" />
					<AlertTitle>No Titles Found</AlertTitle>
					<AlertDescription>
						This library doesn't have any titles yet.
					</AlertDescription>
				</Alert>
				<div className="mt-6">
					<Link to="/home">
						<Button variant="outline">
							<ArrowLeft className="mr-2 h-4 w-4" />
							Back to Home
						</Button>
					</Link>
				</div>
			</div>
		);
	}

	const { titles, pagination } = data;

	return (
		<div className="container mx-auto px-4 py-8">
			<div className="mb-6 flex items-center justify-between">
				<h1 className="font-bold text-2xl">Library Titles</h1>
				<div className="text-muted-foreground text-sm">
					{pagination.total} {pagination.total === 1 ? "title" : "titles"}
				</div>
			</div>

			{/* Titles Grid */}
			<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
				{titles.map((title) => (
					<MovieCard
						key={title.id}
						id={title.id}
						imageUrl={title.poster ?? undefined}
						title={title.title}
						description={title.year || ""}
					/>
				))}
			</div>

			{/* Pagination Controls */}
			{pagination.totalPages > 1 && (
				<div className="mt-8 flex items-center justify-center gap-4">
					<Button
						variant="outline"
						size="sm"
						onClick={() => updatePage(Math.max(1, page - 1))}
						disabled={page === 1}
					>
						<ChevronLeft className="mr-1 h-4 w-4" />
						Previous
					</Button>
					<span className="text-muted-foreground text-sm">
						Page {page} of {pagination.totalPages}
					</span>
					<Button
						variant="outline"
						size="sm"
						onClick={() =>
							updatePage(Math.min(pagination.totalPages, page + 1))
						}
						disabled={page === pagination.totalPages}
					>
						Next
						<ChevronRight className="ml-1 h-4 w-4" />
					</Button>
				</div>
			)}
		</div>
	);
}
