import type { Models } from "@nontara/server/models";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import {
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from "@/components/ui/select";
import { useTRPC } from "@/utils/trpc";
import { EpisodeCard } from "./EpisodeCard";

type EpisodesListProps = {
	titleId: string;
	seasons: Models.SeriesSeason[];
};

export function EpisodesList({ titleId, seasons }: EpisodesListProps) {
	const trpc = useTRPC();
	const [selectedSeason, setSelectedSeason] = useState(
		seasons[0]?.seasonId || "1",
	);

	const { data: episodesData, isLoading } = useQuery(
		trpc.title.getSeasonEpisodes.queryOptions({
			titleId,
			seasonId: selectedSeason,
		}),
	);

	return (
		<div className="space-y-6">
			{/* Header */}
			<div className="flex items-center justify-between">
				<h2 className="font-semibold text-2xl">Episodes</h2>
				<Select value={selectedSeason} onValueChange={setSelectedSeason}>
					<SelectTrigger className="w-[180px] border-border/50 bg-card/50">
						<SelectValue placeholder="Select season" />
					</SelectTrigger>
					<SelectContent>
						{seasons.map((season) => (
							<SelectItem key={season.seasonId} value={season.seasonId}>
								{season.title ? (
									<>
										S{String(season.seasonNumber).padStart(2, "0")}:{" "}
										<span className="text-muted-foreground">
											{season.title}
										</span>
									</>
								) : (
									`Season ${season.seasonNumber}`
								)}
							</SelectItem>
						))}
					</SelectContent>
				</Select>
			</div>

			{/* Episodes List */}
			<div className="space-y-4">
				{isLoading ? (
					<div className="flex items-center justify-center p-8">
						<p className="text-muted-foreground text-sm">Loading episodes...</p>
					</div>
				) : episodesData?.episodes.length === 0 ? (
					<div className="flex items-center justify-center p-8">
						<p className="text-muted-foreground text-sm">
							No episodes available
						</p>
					</div>
				) : (
					episodesData?.episodes.map((episode) => (
						<EpisodeCard key={episode.id} episode={episode} />
					))
				)}
			</div>
		</div>
	);
}
