import { useQuery } from "@tanstack/react-query";
import { createFileRoute, Link } from "@tanstack/react-router";
import { AlertCircle, ArrowLeft, Loader2 } from "lucide-react";
import TitleDetails from "@/components/nontora/TitleDetails";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { parseTRPCError } from "@/lib/trpc-errors";
import { useTRPC } from "@/utils/trpc";

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

function RouteComponent() {
	const { id } = Route.useParams();
	const trpc = useTRPC();

	const { data, isLoading, error } = useQuery(
		trpc.title.getDetails.queryOptions({ id }),
	);

	// Loading state
	if (isLoading) {
		return (
			<div className="flex h-screen items-center justify-center">
				<div className="text-center">
					<Loader2 className="mx-auto h-12 w-12 animate-spin text-primary" />
					<p className="mt-4 text-muted-foreground">Loading title details...</p>
				</div>
			</div>
		);
	}

	// Error state
	if (error) {
		const errorInfo = parseTRPCError(error);
		return (
			<div className="container mx-auto px-4 py-6 sm:px-6 sm:py-12">
				<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" className="w-full sm:w-auto">
							<ArrowLeft className="mr-2 h-4 w-4" />
							Back to Home
						</Button>
					</Link>
				</div>
			</div>
		);
	}

	// Success state
	if (!data) {
		return (
			<div className="container mx-auto px-4 py-6 sm:px-6 sm:py-12">
				<Alert>
					<AlertCircle className="h-4 w-4" />
					<AlertTitle>No Data</AlertTitle>
					<AlertDescription>
						No title data was returned from the server.
					</AlertDescription>
				</Alert>
				<div className="mt-6">
					<Link to="/home">
						<Button variant="outline" className="w-full sm:w-auto">
							<ArrowLeft className="mr-2 h-4 w-4" />
							Back to Home
						</Button>
					</Link>
				</div>
			</div>
		);
	}

	return <TitleDetails data={data} />;
}
