import { useNavigate } from "@tanstack/react-router";
import {
	Bookmark,
	Calendar,
	Clock,
	Film,
	Play,
	Share2,
	Star,
} from "lucide-react";
import { useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { formatRuntime } from "@/lib/format";
import type { GetTitleDetailsOutput } from "../../../../server/src/models/trpc/titles";
import CastSection from "./CastSection";
import CrewSection from "./CrewSection";
import { EpisodesList } from "./EpisodeList";
import MediaTracksSelector from "./MediaTracksSelector";
import SimilarTitlesSection from "./SimilarTitlesSection";

type TitleDetailsProps = {
	data: GetTitleDetailsOutput;
};

export default function TitleDetails({ data }: TitleDetailsProps) {
	const navigate = useNavigate();
	const [selectedTracks, setSelectedTracks] = useState<{
		video?: number;
		audio?: number;
		subtitle?: number;
	}>({});

	const getEndTime = (runtimeSeconds: number) => {
		const endTime = new Date(Date.now() + runtimeSeconds * 1000);
		return endTime.toLocaleTimeString(undefined, {
			hour: "2-digit",
			minute: "2-digit",
		});
	};

	const handlePlay = () => {
		navigate({
			to: "/watch/$id",
			params: { id: data.id },
			search: {
				asi: selectedTracks.audio,
				ssi: selectedTracks.subtitle,
			},
		});
	};

	return (
		<div className="relative min-h-[calc(100vh-4rem)]">
			{/* Backdrop with gradient overlay */}
			<div className="absolute inset-0 h-[50vh] sm:h-[60vh] lg:h-[80vh]">
				{data.backdrop && (
					<img
						src={data.backdrop}
						alt={`${data.title} backdrop`}
						className="h-full w-full object-cover"
					/>
				)}
				<div className="absolute inset-0 bg-gradient-to-t from-background via-background/80 to-background/20" />
				<div className="absolute inset-0 bg-gradient-to-r from-background via-transparent to-background/60" />
			</div>

			{/* Content */}
			<div className="relative z-10">
				{/* Main Content */}
				<div className="container mx-auto px-4 py-6 sm:px-6 sm:py-12">
					<div className="grid grid-cols-1 items-start gap-6 sm:gap-8 lg:grid-cols-3 lg:gap-12">
						{/* Poster */}
						<div className="mx-auto w-full max-w-[200px] sm:max-w-xs md:max-w-sm lg:col-span-1 lg:max-w-none">
							<Card className="overflow-hidden border-border/50 bg-card/50 p-0 backdrop-blur-sm">
								<img
									src={data.poster ?? "/movie-placeholder.svg"}
									alt={`${data.title} poster`}
									className="w-full object-contain"
								/>
							</Card>
						</div>

						{/* Movie Info */}
						<div className="min-w-0 space-y-4 sm:space-y-6 lg:col-span-2">
							{/* Title and Basic Info */}
							<div className="space-y-2 sm:space-y-3">
								<h1 className="text-balance break-words font-bold text-2xl leading-tight sm:text-3xl md:text-4xl lg:text-5xl xl:text-6xl">
									{data.title}
								</h1>

								{data.originalTitle && data.originalTitle !== data.title && (
									<div className="inline-block rounded-md bg-muted px-3 py-1 text-muted-foreground text-sm">
										{data.originalTitle}
									</div>
								)}

								<div className="flex flex-wrap items-center gap-2 text-muted-foreground text-xs sm:gap-3 sm:text-sm">
									{data.year && (
										<span className="flex items-center gap-1">
											<Calendar className="h-4 w-4" />
											{data.year}
										</span>
									)}

									{data.type === "MOVIE" && data.runtimeSeconds && (
										<>
											<span className="flex items-center gap-1">
												<Clock className="h-4 w-4" />
												{formatRuntime(data.runtimeSeconds)}
											</span>
											<span className="flex items-center gap-1">
												• Ends at {getEndTime(data.runtimeSeconds)}
											</span>
										</>
									)}

									{data.type === "SERIES" && (
										<span className="flex items-center gap-1">
											<Film className="h-4 w-4" />
											{data.seasonsCount}{" "}
											{data.seasonsCount === 1 ? "Season" : "Seasons"} •{" "}
											{data.episodesCount}{" "}
											{data.episodesCount === 1 ? "Episode" : "Episodes"}
										</span>
									)}

									{data.rating && (
										<div className="flex items-center gap-1">
											<Star className="h-4 w-4 fill-primary text-primary" />
											<span className="font-medium text-foreground">
												{data.rating.toFixed(1)}
											</span>
										</div>
									)}
								</div>

								<div className="flex flex-wrap gap-1.5 sm:gap-2">
									{data.genres.map((genre) => (
										<Badge
											key={genre.id}
											variant="secondary"
											className="bg-secondary/50 text-secondary-foreground text-xs sm:text-sm"
										>
											{genre.name}
										</Badge>
									))}
								</div>
							</div>

							{/* Action Buttons */}
							<div className="flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:gap-3">
								<Button
									size="lg"
									className="w-full bg-primary text-primary-foreground hover:bg-primary/90 sm:w-auto"
									onClick={handlePlay}
								>
									<Play className="mr-2 h-5 w-5" />
									Play
								</Button>
								<Button
									variant="outline"
									size="lg"
									className="w-full sm:w-auto"
								>
									<Bookmark className="mr-2 h-5 w-5" />
									Watchlist
								</Button>
								<Button
									variant="outline"
									size="lg"
									className="w-full sm:w-auto"
								>
									<Share2 className="mr-2 h-5 w-5" />
									Share
								</Button>
							</div>

							{/* Synopsis */}
							<div className="space-y-2 sm:space-y-3">
								<h2 className="font-semibold text-lg sm:text-xl">Synopsis</h2>
								<p className="text-pretty text-muted-foreground text-sm leading-relaxed sm:text-base">
									{data.synopsis ?? "No synopsis available."}
								</p>
							</div>

							{/* Media Tracks - Only for Movies */}
							{data.type === "MOVIE" && (
								<MediaTracksSelector
									titleId={data.id}
									onTracksChange={setSelectedTracks}
								/>
							)}

							{/* Episodes - Only for Series */}
							{data.type === "SERIES" && data.seasons.length > 0 && (
								<EpisodesList titleId={data.id} seasons={data.seasons} />
							)}

							{/* Cast */}
							{data.cast.length > 0 && <CastSection cast={data.cast} />}

							{/* Crew */}
							{data.crew.length > 0 && <CrewSection crew={data.crew} />}

							{/* Similar Titles */}
							{data.similarTitles.length > 0 && (
								<SimilarTitlesSection titles={data.similarTitles} />
							)}
						</div>
					</div>
				</div>
			</div>
		</div>
	);
}
