import type { Metadata } from "next";
import { getBook, getBooks } from "@/lib/data";
import RecommendedBooks from "@/components/web/books/RecommendedBooks";
import { notFound } from "next/navigation";
import Image from "next/image";
import { BookOpen, Clock, Star, MapPin, Bookmark } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { getPublicUrl } from "@/lib/utils/storage";
import BorrowActions from "@/components/web/books/BorrowActions";
import { auth } from "@/lib/auth"
import { headers } from "next/headers"
import { prisma } from "@/lib/prisma";
import ReviewForm from "@/components/web/books/ReviewForm";

export async function generateMetadata({ params }: { params: Promise<{ id: string }> }): Promise<Metadata> {
  const { id } = await params;
  const book = await getBook(id);

  if (!book) {
    return {
      title: "Book Not Found | E-Library",
      description: "The requested book could not be found in the E-Library.",
    };
  }

  return {
    title: `${book.title} | E-Library`,
    description: book.description ?? `Read details and borrow ${book.title} from the Federal Polytechnic Bali E-Library.`,
  };
}

export default async function BookDetailsPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const book = await getBook(id);
  const books = await getBooks();

  if (!book) {
    notFound();
  }

  // Inside BookDetailsPage, after fetching the book:
  const session = await auth.api.getSession({ headers: await headers() })

  const existingLoan = session ? await prisma.loan.findFirst({
    where: {
      userId: session.user.id,
      bookId: book.id,
      status: { in: ["ACTIVE", "OVERDUE"] }
    }
  }) : null

  const existingReservation = session ? await prisma.reservation.findFirst({
    where: {
      userId: session.user.id,
      bookId: book.id,
      status: "PENDING"
    }
  }) : null


  const thumbnailSrc = getPublicUrl(book.coverImage || "");

  const rating = 4.8;
  const reviewsCount = 124;
  const format = book.format === "DIGITAL" ? "Digital" : book.format === "PHYSICAL" ? "Physical" : "Digital & Physical";
  const status = "Available";


  const sameCategory = books.filter((b) => b.category === book.category && b.id !== book.id);
  const additionalBooks = books.filter((b) => b.id !== book.id && !sameCategory.some((rb) => rb.id === b.id));
  const fullRecommendations = [...sameCategory, ...additionalBooks].slice(0, 16);


  return (
    <main className="min-h-screen bg-background pb-24">
      {/* Hero Section */}
      <div className="relative w-full h-[40vh] sm:h-[50vh] bg-primary overflow-hidden">
        {/* Background blur effect */}
        <div className="absolute inset-0 opacity-20">
          <Image
            src={thumbnailSrc}
            alt={book.title}
            fill
            className="object-cover blur-3xl scale-110"
            priority
          />
        </div>
        <div className="absolute inset-0 bg-gradient-to-t from-background via-background/60 to-transparent" />
      </div>

      {/* Content Container */}
      <div className="max-w-6xl mx-auto px-6 sm:px-12 -mt-32 relative z-20 flex flex-col md:flex-row gap-10">
        
        {/* Left Col - Cover Image */}
        <div className="w-full md:w-1/3 lg:w-1/4 shrink-0 flex flex-col items-center md:items-start">
          <div className="relative w-48 md:w-full aspect-[2/3] rounded-xl shadow-2xl overflow-hidden border-4 border-background bg-muted">
            <Image
              src={thumbnailSrc}
              alt={book.title}
              fill
              className="object-cover"
              priority
              sizes="(max-width: 768px) 192px, 300px"
            />
          </div>
          
          <div className="w-full mt-8 p-6 bg-accent rounded-2xl shadow-sm border border-border/50 backdrop-blur-xl">
            <div className="flex justify-between items-center mb-4">
              <span className="text-sm text-muted-foreground font-medium">Status</span>
              <Badge variant="default" className="bg-green-500/10 text-green-600 hover:bg-green-500/20 border-green-500/20">
                {status}
              </Badge>
            </div>
            <Separator className="mb-4 bg-border/50" />
            <BorrowActions
              bookId={book.id}
              format={book.format}
              hasActiveLoan={!!existingLoan}
              hasActiveReservation={!!existingReservation}
            />
          </div>
        </div>

        {/* Right Col - Details */}
        <div className="flex-1 pt-4 md:pt-16 pb-12">
          <div className="flex items-center gap-3 mb-4 flex-wrap">
            <Badge variant="secondary" className="px-3 py-1 rounded-full bg-primary/10 text-primary border-primary/20 text-xs font-semibold tracking-wider uppercase">
              {book.category}
            </Badge>
            <span className="flex items-center text-sm text-yellow-500 font-medium">
              <Star className="w-4 h-4 mr-1 fill-yellow-500" />
              {rating} <span className="text-muted-foreground ml-1">({reviewsCount} reviews)</span>
            </span>
          </div>

          <h1 className="text-4xl sm:text-5xl lg:text-6xl font-bold tracking-tight text-foreground mb-2">
            {book.title}
          </h1>
          <p className="text-xl sm:text-2xl text-muted-foreground font-light mb-8">
            by <span className="text-foreground font-medium hover:underline cursor-pointer">{book.author}</span>
          </p>

          <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mb-10 p-6 rounded-2xl bg-muted/30 border border-border/40">
            <div className="flex flex-col">
              <span className="text-xs text-muted-foreground uppercase tracking-wider font-semibold mb-1 flex items-center gap-1.5">
                <BookOpen className="w-3.5 h-3.5" /> Pages
              </span>
              <span className="text-lg font-medium">{book.pages}</span>
            </div>
            <div className="flex flex-col">
              <span className="text-xs text-muted-foreground uppercase tracking-wider font-semibold mb-1 flex items-center gap-1.5">
                <Clock className="w-3.5 h-3.5" /> Published
              </span>
              <span className="text-lg font-medium">{book.publishedDate || "Unknown"}</span>
            </div>
            <div className="flex flex-col">
              <span className="text-xs text-muted-foreground uppercase tracking-wider font-semibold mb-1 flex items-center gap-1.5">
                <Bookmark className="w-3.5 h-3.5" /> Format
              </span>
              <span className="text-lg font-medium">{format}</span>
            </div>
            <div className="flex flex-col">
              <span className="text-xs text-muted-foreground uppercase tracking-wider font-semibold mb-1 flex items-center gap-1.5">
                <MapPin className="w-3.5 h-3.5" /> Location
              </span>
              <span className="text-lg font-medium">{book.location || "Unknown"}</span>
            </div>
          </div>

          <Tabs defaultValue="about" className="w-full">
            <TabsList className="w-full justify-start h-auto p-0 bg-transparent border-b border-border rounded-none mb-6 flex-wrap gap-y-2">
              <TabsTrigger 
                value="about" 
                className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none px-6 py-3 text-base font-medium transition-all"
              >
                About
              </TabsTrigger>
              <TabsTrigger 
                value="reviews" 
                className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none px-6 py-3 text-base font-medium transition-all"
              >
                Reviews
              </TabsTrigger>
              <TabsTrigger 
                value="details" 
                className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none px-6 py-3 text-base font-medium transition-all"
              >
                Details
              </TabsTrigger>
            </TabsList>
            
            <TabsContent value="about" className="animate-in fade-in slide-in-from-bottom-4 duration-500">
              <div className="prose prose-neutral dark:prose-invert max-w-none">
                <p className="text-lg leading-relaxed text-muted-foreground font-light">
                  {book.description}
                </p>
              </div>
            </TabsContent>

            <TabsContent value="reviews" className="animate-in fade-in slide-in-from-bottom-4 duration-500">
              <div className="space-y-6">
                {book.reviews.length === 0 ? (
                  <p className="text-sm text-muted-foreground text-center py-8">
                    No reviews yet. Be the first to review this book.
                  </p>
                ) : (
                  book.reviews.map((review) => (
                    <div key={review.id} className="flex gap-4 p-5 rounded-xl bg-accent/50 border border-border/40">
                      <Avatar className="w-10 h-10 border border-border">
                        <AvatarFallback>
                          {review.user.name?.charAt(0).toUpperCase() ?? "U"}
                        </AvatarFallback>
                      </Avatar>
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <span className="font-semibold text-sm">{review.user.name ?? "Anonymous"}</span>
                          <span className="text-xs text-muted-foreground">
                            {new Date(review.createdAt).toLocaleDateString()}
                          </span>
                        </div>
                        <div className="flex text-yellow-500 mb-2">
                          {[...Array(5)].map((_, i) => (
                            <Star
                              key={i}
                              className={`w-3 h-3 ${i < review.rating ? "fill-yellow-500" : "text-muted stroke-muted-foreground"}`}
                            />
                          ))}
                        </div>
                        <p className="text-sm text-muted-foreground leading-relaxed">
                          {review.comment}
                        </p>
                      </div>
                    </div>
                  ))
                )}

                {/* Review form — only shown if student has active loan */}
                {existingLoan && (
                  <ReviewForm bookId={book.id} existingReview={!!book.reviews.find(r => r.userId === session?.user.id)} />
                )}
              </div>
            </TabsContent>
            
            <TabsContent value="details" className="animate-in fade-in slide-in-from-bottom-4 duration-500">
               <dl className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-4 text-sm">
                 <div className="flex flex-col gap-1 py-3 border-b border-border/50">
                   <dt className="text-muted-foreground">Publisher</dt>
                   <dd className="font-medium">Federal Polytechnic, Bali</dd>
                 </div>
                 <div className="flex flex-col gap-1 py-3 border-b border-border/50">
                   <dt className="text-muted-foreground">Language</dt>
                   <dd className="font-medium">{book.language}</dd>
                 </div>
                 <div className="flex flex-col gap-1 py-3 border-b border-border/50">
                   <dt className="text-muted-foreground">ISBN Number</dt>
                   <dd className="font-medium">{book.isbn}</dd>
                 </div>
                 <div className="flex flex-col gap-1 py-3 border-b border-border/50">
                   <dt className="text-muted-foreground">Pages</dt>
                   <dd className="font-medium">{book.pages}</dd>
                 </div>
                 <div className="flex flex-col gap-1 py-3 border-b border-border/50">
                   <dt className="text-muted-foreground">Category</dt>
                   <dd className="font-medium">{book.category}</dd>
                 </div>
                 <div className="flex flex-col gap-1 py-3 border-b border-border/50">
                   <dt className="text-muted-foreground">Format</dt>
                   <dd className="font-medium">{format}</dd>
                 </div>
               </dl>
            </TabsContent>
          </Tabs>

        </div>
      </div>

      {/* Recommended Books Section */}
      <RecommendedBooks books={fullRecommendations} />
    </main>
  );
}
