import { useQuery } from "@tanstack/react-query";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { AlertCircle, Search } from "lucide-react";
import * as React from "react";
import MovieCard from "@/components/nontora/MovieCard";
import {
	Empty,
	EmptyDescription,
	EmptyHeader,
	EmptyMedia,
	EmptyTitle,
} from "@/components/ui/empty";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import { useTRPC } from "@/utils/trpc";

type TitleSearchParams = {
	q?: string;
};

export const Route = createFileRoute("/home/search")({
	component: RouteComponent,
	validateSearch: (search: Record<string, unknown>): TitleSearchParams => {
		return {
			q: typeof search.q === "string" ? search.q : undefined,
		};
	},
	head: () => ({
		meta: [
			{
				title: "Search - Nontara",
			},
		],
	}),
});

function RouteComponent() {
	const trpc = useTRPC();
	const navigate = useNavigate({ from: Route.fullPath });
	const { q: searchQuery = "" } = Route.useSearch();
	const [inputValue, setInputValue] = React.useState(searchQuery);

	// Sync input value with URL param when it changes externally
	React.useEffect(() => {
		setInputValue(searchQuery);
	}, [searchQuery]);

	// Debounce URL update
	React.useEffect(() => {
		const timer = setTimeout(() => {
			navigate({
				search: (prev) => ({ ...prev, q: inputValue || undefined }),
				replace: true,
			});
		}, 300);

		return () => clearTimeout(timer);
	}, [inputValue, navigate]);

	const { data, isLoading, error } = useQuery(
		trpc.title.search.queryOptions(
			{ query: searchQuery },
			{
				enabled: searchQuery.length > 0,
			},
		),
	);

	return (
		<div className="container mx-auto px-4 py-6">
			{/* Centered Search Input */}
			<div className="mx-auto mb-6 max-w-2xl">
				<div className="relative">
					<Search className="absolute top-3 left-3 h-5 w-5 text-muted-foreground" />
					<Input
						type="text"
						placeholder="Search for movies and series..."
						value={inputValue}
						onChange={(e) => setInputValue(e.target.value)}
						className="h-12 pl-10 text-base"
					/>
				</div>
			</div>

			{/* Results Section */}
			<div>
				{/* Empty State */}
				{!searchQuery && (
					<Empty className="min-h-[300px]">
						<EmptyHeader>
							<EmptyMedia variant="icon">
								<Search />
							</EmptyMedia>
							<EmptyTitle>Search for titles</EmptyTitle>
							<EmptyDescription>
								Start typing to search for movies and series
							</EmptyDescription>
						</EmptyHeader>
					</Empty>
				)}

				{/* Loading State */}
				{searchQuery && isLoading && (
					<div className="grid grid-cols-2 gap-2 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} className="flex flex-col gap-2">
								<Skeleton className="aspect-[3/4] w-full rounded-lg" />
								<Skeleton className="h-4 w-full" />
								<Skeleton className="h-3 w-3/4" />
							</div>
						))}
					</div>
				)}

				{/* Error State */}
				{searchQuery && error && (
					<Empty className="min-h-[300px]">
						<EmptyHeader>
							<EmptyMedia variant="icon">
								<AlertCircle className="text-destructive" />
							</EmptyMedia>
							<EmptyTitle>Failed to load results</EmptyTitle>
							<EmptyDescription className="text-destructive">
								Something went wrong. Please try again.
							</EmptyDescription>
						</EmptyHeader>
					</Empty>
				)}

				{/* Results State */}
				{searchQuery && !isLoading && data && data.length > 0 && (
					<div>
						<p className="mb-3 text-muted-foreground text-sm">
							Found {data.length} result{data.length > 1 ? "s" : ""} for "
							{searchQuery}"
						</p>
						<div className="grid grid-cols-2 gap-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
							{data.map((title) => (
								<MovieCard
									key={title.id}
									id={title.id}
									title={title.title}
									imageUrl={title.poster ?? undefined}
									description={title.year || title.type}
								/>
							))}
						</div>
					</div>
				)}

				{/* No Results State */}
				{searchQuery && !isLoading && data && data.length === 0 && (
					<Empty className="min-h-[300px]">
						<EmptyHeader>
							<EmptyMedia variant="icon">
								<Search />
							</EmptyMedia>
							<EmptyTitle>No results found</EmptyTitle>
							<EmptyDescription>
								No titles found for "{searchQuery}"
							</EmptyDescription>
						</EmptyHeader>
					</Empty>
				)}
			</div>
		</div>
	);
}
