import { useQueryClient } from "@tanstack/react-query";
import {
	ArrowLeft,
	Bell,
	BellOff,
	BookOpen,
	Calendar,
	ChevronDown,
	Database,
	Heart,
	Star,
} from "lucide-react";
import { useCallback, useState } from "react";
import { useNavigate, useParams } from "react-router";
import { toast } from "sonner";
import {
	useSetFavorite,
	useSetUnfavorite,
} from "@/api/generated/favorite-mangas/favorite-mangas.ts";
import {
	useFetchMangaChapters,
	useFollowManga,
	useGetManga,
	useUnfollowManga,
} from "@/api/generated/manga/manga.ts";
import { useFetchAllChapters } from "@/api/generated/manga-chapter/manga-chapter.ts";
import { ThemeToggle } from "@/components/ThemeToggle.tsx";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
	Collapsible,
	CollapsibleContent,
	CollapsibleTrigger,
} from "@/components/ui/collapsible.tsx";
import { useAuth } from "@/contexts/AuthContext.tsx";
import { MangaChapter } from "@/features/manga/MangaChapter.tsx";
import { formatToTwoDigitsDateRange } from "@/utils/dateFormatter.ts";

const Manga = () => {
	const { isAuthenticated } = useAuth();
	const navigate = useNavigate();
	const params = useParams();
	const mangaId = Number(params.mangaId);

	const queryClient = useQueryClient();

	const { data: mangaData, queryKey } = useGetManga(mangaId);

	const { mutate, isPending: fetchPending } = useFetchMangaChapters({
		mutation: {
			onSuccess: () => queryClient.invalidateQueries({ queryKey }),
		},
	});

	const { mutate: fetchAllMutate, isPending: fetchAllPending } =
		useFetchAllChapters({
			mutation: {
				onSuccess: () => toast.success("Chapter import queued successfully."),
			},
		});

	const isPending = fetchPending || fetchAllPending;

	const [openProviders, setOpenProviders] = useState<Set<number>>(new Set());

	const { mutate: mutateFavorite, isPending: isPendingFavorite } =
		useSetFavorite({
			mutation: {
				onSuccess: () => queryClient.invalidateQueries({ queryKey }),
			},
		});

	const { mutate: mutateUnfavorite, isPending: isPendingUnfavorite } =
		useSetUnfavorite({
			mutation: {
				onSuccess: () => queryClient.invalidateQueries({ queryKey }),
			},
		});

	const isPendingFavoriteChange = isPendingFavorite || isPendingUnfavorite;

	const handleFavoriteClick = useCallback(
		(isFavorite: boolean) => {
			isFavorite
				? mutateUnfavorite({ id: mangaData?.data?.id ?? -1 })
				: mutateFavorite({ id: mangaData?.data?.id ?? -1 });
		},
		[mutateUnfavorite, mutateFavorite, mangaData?.data?.id],
	);

	const { mutate: mutateFollow, isPending: isPendingFollow } = useFollowManga({
		mutation: {
			onSuccess: () => {
				queryClient.invalidateQueries({ queryKey });
				toast.success(
					"We will notify you when new content if available for this manga.",
				);
			},
		},
	});

	const { mutate: mutateUnfollow, isPending: isPendingUnfollow } =
		useUnfollowManga({
			mutation: {
				onSuccess: () => {
					queryClient.invalidateQueries({ queryKey });
					toast.success(
						"You will no longer received notifications for this manga.",
					);
				},
			},
		});

	const isPendingFollowChange = isPendingFollow || isPendingUnfollow;

	const handleFollowClick = useCallback(
		(isFollowing: boolean) => {
			isFollowing
				? mutateUnfollow({ mangaId: mangaData?.data?.id ?? -1 })
				: mutateFollow({ mangaId: mangaData?.data?.id ?? -1 });
		},
		[mangaData?.data?.id, mutateUnfollow, mutateFollow],
	);

	if (!mangaData) {
		return (
			<div className="flex min-h-screen items-center justify-center bg-background">
				<div className="text-center">
					<h1 className="text-2xl font-bold text-foreground">
						Manga not found
					</h1>
					<Button onClick={() => navigate("/")} className="mt-4">
						Go back home
					</Button>
				</div>
			</div>
		);
	}

	const toggleProvider = (providerId: number) => {
		setOpenProviders((prev) => {
			const next = new Set(prev);
			if (next.has(providerId)) {
				next.delete(providerId);
			} else {
				next.add(providerId);
			}
			return next;
		});
	};

	return (
		<div className="min-h-screen bg-background">
			{/* Header */}
			<header className="border-b border-border bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
				<div className="px-8 py-6">
					<div className="flex items-center justify-between">
						<div className="flex items-center gap-6">
							<Button
								variant="ghost"
								onClick={() => navigate("/")}
								className="gap-2"
							>
								<ArrowLeft className="h-4 w-4" />
								Back to Library
							</Button>
							<h1 className="text-xl font-bold text-foreground">MangaMochi</h1>
						</div>
						<ThemeToggle />
					</div>
				</div>
			</header>

			{/* Content */}
			<main className="px-8 py-8">
				<div className="mx-auto max-w-7xl">
					{/* Manga Info Section */}
					<div className="grid gap-8 lg:grid-cols-[300px_1fr]">
						{/* Cover */}
						<div className="relative aspect-[2/3] overflow-hidden rounded-lg border border-border bg-muted lg:sticky lg:top-8 lg:h-fit">
							<img
								src={
									(mangaData.data?.coverImageKey &&
										import.meta.env.VITE_OMV_BASE_URL +
											"/" +
											mangaData.data?.coverImageKey) ||
									"/placeholder.svg"
								}
								alt={mangaData.data?.title ?? ""}
								className="absolute inset-0 w-full h-full object-cover"
							/>
						</div>

						{/* Details */}
						<div className="space-y-6">
							<div>
								<div className="mb-3 flex items-center justify-between gap-4">
									<h1 className="text-balance text-4xl font-bold tracking-tight text-foreground">
										{mangaData.data?.title}
									</h1>
									<div className="flex gap-4 items-center">
										<Badge
											variant="secondary"
											className="border border-border bg-card text-foreground max-h-6"
										>
											{mangaData.data?.status}
										</Badge>

										{isAuthenticated && (
											<>
												<Button
													size="icon"
													variant="outline"
													onClick={(event) => {
														event.preventDefault();
														event.stopPropagation();
														handleFollowClick(
															mangaData?.data?.following || false,
														);
													}}
													disabled={isPendingFollowChange}
												>
													{mangaData?.data?.following ? <BellOff /> : <Bell />}
												</Button>
												<Button
													size="icon"
													variant="outline"
													onClick={(event) => {
														event.preventDefault();
														event.stopPropagation();
														handleFavoriteClick(
															mangaData?.data?.favorite || false,
														);
													}}
													disabled={isPendingFavoriteChange}
												>
													<Heart
														className={`h-4 w-4 transition-colors ${
															mangaData?.data?.favorite
																? "fill-red-500 text-red-500"
																: "text-muted-foreground hover:text-red-500"
														}`}
													/>
												</Button>
											</>
										)}
									</div>
								</div>
								<p className="text-lg text-muted-foreground">
									{mangaData.data?.authors.join(", ")}
								</p>
							</div>

							{mangaData.data?.alternativeTitles &&
								mangaData.data?.alternativeTitles.length > 0 && (
									<div>
										<h3 className="mb-2 text-sm font-medium text-muted-foreground">
											Alternative Titles
										</h3>
										<div className="flex flex-wrap gap-2">
											{mangaData.data?.alternativeTitles.map((title, index) => (
												<span
													key={index}
													className="rounded-md bg-muted px-3 py-1 text-sm text-foreground"
												>
													{title}
												</span>
											))}
										</div>
									</div>
								)}

							<p className="text-pretty text-justify leading-relaxed text-foreground">
								{mangaData.data?.synopsis}
							</p>

							<div className="grid gap-4 sm:grid-cols-2">
								<div className="flex items-center gap-3 rounded-lg border border-border bg-card p-4">
									<Star className="h-5 w-5 fill-primary text-primary" />
									<div>
										<p className="text-sm text-muted-foreground">Rating</p>
										<p className="text-lg font-semibold text-foreground">
											{mangaData.data?.score && mangaData.data?.score > 0
												? mangaData.data?.score
												: "-"}
										</p>
									</div>
								</div>

								<div className="flex items-center gap-3 rounded-lg border border-border bg-card p-4">
									<BookOpen className="h-5 w-5 text-primary" />
									<div>
										<p className="text-sm text-muted-foreground">Chapters</p>
										<p className="text-lg font-semibold text-foreground">
											{mangaData.data?.chapterCount &&
											mangaData.data?.chapterCount > 0
												? mangaData.data?.chapterCount
												: "-"}
										</p>
									</div>
								</div>

								{mangaData?.data?.publishedFrom && (
									<div className="flex items-center gap-3 rounded-lg border border-border bg-card p-4">
										<Calendar className="h-5 w-5 text-primary" />
										<div>
											<p className="text-sm text-muted-foreground">Published</p>
											<p className="text-lg font-semibold text-foreground">
												{formatToTwoDigitsDateRange(
													mangaData.data.publishedFrom,
													mangaData?.data?.publishedTo,
												)}
											</p>
										</div>
									</div>
								)}

								<div className="flex items-center gap-3 rounded-lg border border-border bg-card p-4">
									<Database className="h-5 w-5 text-primary" />
									<div>
										<p className="text-sm text-muted-foreground">Providers</p>
										<p className="text-lg font-semibold text-foreground">
											{mangaData.data?.providerCount}
										</p>
									</div>
								</div>
							</div>

							<div className="flex flex-wrap gap-2">
								{mangaData.data?.genres.map((genre) => (
									<Badge
										key={genre}
										variant="outline"
										className="border-border text-foreground"
									>
										{genre}
									</Badge>
								))}
							</div>
						</div>
					</div>

					<div className="mt-12">
						<h2 className="mb-6 text-2xl font-bold text-foreground">
							Chapters by Provider
						</h2>

						<div className="space-y-4">
							{mangaData.data?.providers.map((provider) => (
								<Card key={provider.id} className="border-border bg-card">
									<Collapsible
										open={openProviders.has(provider.id)}
										onOpenChange={() => toggleProvider(provider.id)}
									>
										<CollapsibleTrigger className="w-full">
											<CardContent className="flex items-center justify-between p-4">
												<div className="flex items-center justify-between w-full">
													<div className="flex items-center gap-4">
														<Database className="h-5 w-5 text-primary" />
														<div className="text-left">
															<p className="font-semibold text-foreground">
																{provider.providerName}
															</p>
															<p className="text-sm text-muted-foreground">
																{provider.chaptersDownloaded} downloaded •{" "}
																{provider.chaptersAvailable} available
															</p>
														</div>
													</div>
													{provider.supportsChapterFetch && (
														<div className={"flex gap-4 pr-4"}>
															<Button
																size="sm"
																variant="outline"
																disabled={isPending}
																onClick={() =>
																	fetchAllMutate({
																		mangaProviderId: provider.id,
																	})
																}
																className="gap-2"
															>
																<Database className="h-4 w-4" />
																Fetch all from Provider
															</Button>
															<Button
																size="sm"
																variant="outline"
																disabled={isPending}
																onClick={() =>
																	mutate({ mangaProviderId: provider.id })
																}
																className="gap-2"
															>
																<Database className="h-4 w-4" />
																Fetch from Provider
															</Button>
														</div>
													)}
												</div>
												<ChevronDown
													className={`h-5 w-5 text-muted-foreground transition-transform ${
														openProviders.has(provider.id) ? "rotate-180" : ""
													}`}
												/>
											</CardContent>
										</CollapsibleTrigger>
										<CollapsibleContent>
											<MangaChapter
												mangaId={mangaId}
												mangaProviderId={provider.id}
											/>
										</CollapsibleContent>
									</Collapsible>
								</Card>
							))}
						</div>
					</div>
				</div>
			</main>
		</div>
	);
};

export default Manga;
