import { useQuery } from "@tanstack/react-query";
import * as React from "react";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { useTRPC } from "@/utils/trpc";
import {
	HorizontalScrollList,
	type HorizontalScrollListRef,
} from "./layout/HorizontalScrollList";
import MovieCard from "./MovieCard";

const RecentlyAddedSections: React.FC = () => {
	const trpc = useTRPC();
	const scrollListRef = React.useRef<HorizontalScrollListRef>(null);
	const [canScrollLeft, setCanScrollLeft] = React.useState(false);
	const [canScrollRight, setCanScrollRight] = React.useState(false);

	const handleScrollableChange = React.useCallback(
		(left: boolean, right: boolean) => {
			setCanScrollLeft(left);
			setCanScrollRight(right);
		},
		[],
	);

	const {
		data: recentlyAddedMovies,
		isLoading,
		error,
		refetch,
	} = useQuery(
		trpc.media.getRecentlyAdded.queryOptions(
			{ limit: 10 },
			{
				retry: 3,
				retryDelay: (attemptIndex: number) =>
					Math.min(1000 * 2 ** attemptIndex, 30000),
				staleTime: 5 * 60 * 1000, // 5 minutes
				refetchOnWindowFocus: false,
			},
		),
	);

	// Loading skeleton
	if (isLoading) {
		return (
			<div className="w-full rounded-lg p-6 shadow-sm">
				<div className="pb-2 sm:pb-3">
					<h3 className="font-semibold text-base sm:text-lg md:text-xl">
						Recently Added
					</h3>
				</div>
				<div className="px-2 sm:px-4">
					<div className="flex space-x-2 overflow-hidden">
						{Array.from({ length: 5 }).map((_, index) => (
							<div
								key={`skeleton-${Date.now()}-${index}`}
								className="flex-none"
								style={{ width: "150px" }}
							>
								<Skeleton className="aspect-[2/3] w-full rounded-xl" />
								<Skeleton className="mt-2 h-4 w-full" />
								<Skeleton className="mt-1 h-3 w-3/4" />
							</div>
						))}
					</div>
				</div>
			</div>
		);
	}

	// Error state with retry
	if (error) {
		return (
			<div className="w-full rounded-lg p-6 shadow-sm">
				<div className="pb-2 sm:pb-3">
					<h3 className="font-semibold text-base sm:text-lg md:text-xl">
						Recently Added
					</h3>
				</div>
				<div>
					<div className="flex flex-col items-center justify-center py-8 text-center">
						<p className="mb-4 text-muted-foreground">
							Failed to load recently added movies
						</p>
						<button
							type="button"
							onClick={() => refetch()}
							className="rounded-md bg-primary px-4 py-2 text-primary-foreground transition-colors hover:bg-primary/90"
						>
							Try Again
						</button>
					</div>
				</div>
			</div>
		);
	}

	// Empty state
	if (!recentlyAddedMovies || recentlyAddedMovies.length === 0) {
		return (
			<div className="w-full rounded-lg p-6 shadow-sm">
				<div className="pb-2 sm:pb-3">
					<h3 className="font-semibold text-base sm:text-lg md:text-xl">
						Recently Added
					</h3>
				</div>
				<div>
					<div className="flex items-center justify-center py-8">
						<p className="text-muted-foreground">No recently added movies</p>
					</div>
				</div>
			</div>
		);
	}

	return (
		<div className="w-full rounded-lg p-6 shadow-sm">
			<div className="pb-2 sm:pb-3">
				<div className="flex items-center justify-between">
					<h3 className="font-semibold text-base sm:text-lg md:text-xl">
						Recently Added
					</h3>
					<div className="flex gap-2">
						<Button
							variant="ghost"
							size="sm"
							onClick={() => scrollListRef.current?.scrollLeft()}
							aria-label="Scroll left"
							disabled={!canScrollLeft}
						>
							←
						</Button>
						<Button
							variant="ghost"
							size="sm"
							onClick={() => scrollListRef.current?.scrollRight()}
							aria-label="Scroll right"
							disabled={!canScrollRight}
						>
							→
						</Button>
					</div>
				</div>
			</div>
			<div className="overflow-hidden">
				<HorizontalScrollList
					ref={scrollListRef}
					className="w-full"
					onScrollableChange={handleScrollableChange}
				>
					{recentlyAddedMovies.map((movie) => (
						<div key={movie.id} className="w-36 flex-none md:w-48">
							<MovieCard
								id={movie.id}
								imageUrl={movie.poster ?? undefined}
								title={movie.title}
								description={movie.year || ""}
							/>
						</div>
					))}
				</HorizontalScrollList>
			</div>
		</div>
	);
};

export default RecentlyAddedSections;
