"use client";

import { useState } from "react";
import { useParams, useRouter } from "next/navigation";
import Image from "next/image";
import {
  ArrowLeft,
  Star,
  Calendar,
  Database,
  BookOpen,
  ChevronDown,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { ThemeToggle } from "@/components/theme-toggle";
import { useFetchMangaChapters, useGetManga } from "@/api/mangamochi";
import { MangaChapter } from "@/components/manga-chapter";
import { useQueryClient } from "@tanstack/react-query";

export default function MangaDetailPage() {
  const params = useParams();
  const router = useRouter();
  const mangaId = Number(params.id);

  const queryClient = useQueryClient();

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

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

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

  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={() => router.push("/")} 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;
    });
  };

  const author = mangaData.data?.authors.join(", ");

  const formatter = new Intl.DateTimeFormat("en-US", {
    month: "2-digit",
    day: "2-digit",
    year: "numeric",
  });

  const publishedTo = mangaData.data?.publishedTo
    ? formatter.format(new Date(mangaData.data.publishedTo))
    : null;
  const publishedFrom = mangaData.data?.publishedFrom
    ? formatter.format(new Date(mangaData.data.publishedFrom))
    : null;

  const dateRange = publishedTo
    ? `${publishedFrom} - ${publishedTo}`
    : `${publishedFrom} - Present`;

  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={() => router.push("/")}
                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">
              <Image
                src={
                  (mangaData.data?.coverImageKey &&
                    "http://omv.badger-pirarucu.ts.net:9000/mangamochi/" +
                      mangaData.data?.coverImageKey) ||
                  "/placeholder.svg"
                }
                alt={mangaData.data?.title ?? ""}
                fill
                className="object-cover"
              />
            </div>

            {/* Details */}
            <div className="space-y-6">
              <div>
                <div className="mb-3 flex items-start justify-between gap-4">
                  <h1 className="text-balance text-4xl font-bold tracking-tight text-foreground">
                    {mangaData.data?.title}
                  </h1>
                  <Badge
                    variant="secondary"
                    className="border border-border bg-card text-foreground"
                  >
                    {mangaData.data?.status}
                  </Badge>
                </div>
                <p className="text-lg text-muted-foreground">{author}</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>

                <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">
                      {dateRange}
                    </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>
                          <div className={"pr-4"}>
                            <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>
  );
}
