import type { Metadata } from "next";
import { getBook } from "@/lib/actions/book"
import { notFound } from "next/navigation"
import Link from "next/link"
import Image from "next/image"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Separator } from "@/components/ui/separator"
import {
  BookOpen, Edit, Star, Users, Copy,
  FileText, MapPin, Calendar, Hash, Globe, ArrowLeft, BookMarked,
} from "lucide-react"
import { getPublicUrl } from "@/lib/utils/storage"
import { bookCopiesColumns } from "./_components/book-copies-columns"
import { bookLoanColumns } from "./_components/book-loans-columns"
import { BookDetailDataTable } from "./_components/DataTable"
import { BackButton } from "@/components/web/backBtn"
import { DeleteBookButton } from "./_components/DeleteBookButton"

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

  if (result.status === "error" || !result.data) {
    return {
      title: "Book Not Found | Admin | E-Library",
      description: "This book could not be found in the admin catalog.",
    };
  }

  const book = result.data;

  return {
    title: `${book.title} | Admin | E-Library`,
    description: book.description ?? `Admin view for ${book.title} in the Federal Polytechnic Bali E-Library.`,
  };
}

export default async function BookDetailPage({ params }: { params: Promise<{ bookId: string }> }) {
  const { bookId } = await params
  const result = await getBook(bookId)

  if (result.status === "error" || !result.data) notFound()

  const book = result.data

  const avgRating =
    book.reviews.length > 0
      ? (book.reviews.reduce((sum, r) => sum + r.rating, 0) / book.reviews.length).toFixed(1)
      : null

  const activeLoans = book.loans.filter((l) => l.status === "ACTIVE").length

  return (
    <div className="min-h-screen">

      {/* ── Header bar ── */}
      <div className="border-b px-6 py-4">
        <div className="max-w-6xl mx-auto flex items-center justify-between">
          <BackButton href="/admin/books" />

          <div className="flex items-center gap-3">
            <Link href={`/admin/books/${bookId}/edit`}>
              <Button size="sm" className="gap-2">
                <Edit className="w-4 h-4" />
                Edit book
              </Button>
            </Link>

            <DeleteBookButton bookId={bookId} bookTitle={book.title} />
          </div>
        </div>
      </div>

      <div className="max-w-6xl mx-auto px-6 py-10 space-y-10">

        {/* ── Hero: cover + core info ── */}
        <div className="flex flex-col md:flex-row gap-8">
          <div className="shrink-0">
            {book.coverImage ? (
              <Image
                src={getPublicUrl(book.coverImage)}
                alt={book.title}
                width={176}
                height={256}
                className="w-44 h-64 object-cover rounded-lg shadow-md border"
              />
            ) : (
              <div className="w-44 h-64 rounded-lg flex items-center justify-center shadow-inner border">
                <BookOpen className="w-12 h-12" />
              </div>
            )}
          </div>

          <div className="flex-1 space-y-4">
            <div>
              <div className="flex flex-wrap items-center gap-2 mb-2">
                <Badge variant="outline" className="text-xs uppercase tracking-wider">
                  {book.format}
                </Badge>
                {book.category && (
                  <Badge variant="secondary" className="text-xs">
                    {book.category.replace(/_/g, " ")}
                  </Badge>
                )}
              </div>
              <h1 className="text-3xl font-bold leading-tight">
                {book.title}
              </h1>
              <p className="text-lg mt-1">by {book.author}</p>
            </div>

            <div className="flex flex-wrap gap-6 text-sm">
              {avgRating && (
                <span className="flex items-center gap-1.5">
                  <Star className="w-4 h-4 text-amber-400 fill-amber-400" />
                  {avgRating} / 5 ({book.reviews.length} review{book.reviews.length !== 1 ? "s" : ""})
                </span>
              )}
              <span className="flex items-center gap-1.5">
                <Users className="w-4 h-4" />
                {activeLoans} active loan{activeLoans !== 1 ? "s" : ""}
              </span>
              {(book.format === "PHYSICAL" || book.format === "BOTH") && (
                <span className="flex items-center gap-1.5">
                  <Copy className="w-4 h-4" />
                  {book.availableCopies}/{book.totalCopies} copies available
                </span>
              )}
              {book.digitalAsset && (
                <span className="flex items-center gap-1.5">
                  <FileText className="w-4 h-4" />
                  {book.digitalAsset.format} available
                </span>
              )}
            </div>

            {book.description && (
              <p className="leading-relaxed max-w-prose">
                {book.description}
              </p>
            )}

            <div className="grid grid-cols-2 sm:grid-cols-3 gap-4 pt-2">
              {book.isbn && <MetaItem icon={<Hash className="w-4 h-4" />} label="ISBN" value={book.isbn} />}
              {book.pages && <MetaItem icon={<BookMarked className="w-4 h-4" />} label="Pages" value={String(book.pages)} />}
              {book.language && <MetaItem icon={<Globe className="w-4 h-4" />} label="Language" value={book.language} />}
              {book.publishedDate && <MetaItem icon={<Calendar className="w-4 h-4" />} label="Published" value={book.publishedDate} />}
              {book.location && <MetaItem icon={<MapPin className="w-4 h-4" />} label="Shelf" value={book.location} />}
            </div>
          </div>
        </div>

        <Separator />

        {/* ── Physical copies — DataTable ── */}
        {book.physicalCopies.length > 0 && (
          <Section title="Physical Copies" count={book.physicalCopies.length}>
            <BookDetailDataTable
              columns={bookCopiesColumns}
              data={book.physicalCopies}
              searchKey="copyCode"
              searchPlaceholder="Search by copy code..."
            />
          </Section>
        )}

        {/* ── Loans — DataTable ── */}
        {book.loans.length > 0 && (
          <Section title="Loan History" count={book.loans.length}>
            <BookDetailDataTable
              columns={bookLoanColumns}
              data={book.loans}
              searchKey="user"
              searchPlaceholder="Search by borrower name or email..."
            />
          </Section>
        )}

        {/* ── Reviews — cards, no table needed ── */}
        {book.reviews.length > 0 && (
          <Section title="Reviews" count={book.reviews.length}>
            <div className="space-y-3">
              {book.reviews.map((review) => (
                <div
                  key={review.id}
                  className="rounded-lg border p-4"
                >
                  <div className="flex items-center justify-between mb-1">
                    <span className="font-medium text-sm">
                      {review.user?.name ?? review.user?.email ?? "Anonymous"}
                    </span>
                    <span className="flex gap-0.5">
                      {Array.from({ length: 5 }).map((_, i) => (
                        <Star
                          key={i}
                          className={`w-3.5 h-3.5 ${
                            i < review.rating
                              ? "text-amber-400 fill-amber-400"
                              : ""
                          }`}
                        />
                      ))}
                    </span>
                  </div>
                  {review.comment && (
                    <p className="text-sm">{review.comment}</p>
                  )}
                </div>
              ))}
            </div>
          </Section>
        )}
      </div>
    </div>
  )
}

// ── Helpers ───────────────────────────────────────────────────────────────────

function MetaItem({ icon, label, value }: { icon: React.ReactNode; label: string; value: string }) {
  return (
    <div className="flex items-start gap-2 text-sm">
      <span className="mt-0.5 text-stone-400">{icon}</span>
      <div>
        <p className="text-xs text-stone-400 uppercase tracking-wide">{label}</p>
        <p className="text-stone-800 dark:text-stone-200 font-medium">{value}</p>
      </div>
    </div>
  )
}

function Section({ title, count, children }: { title: string; count?: number; children: React.ReactNode }) {
  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3">
        <h2 className="text-lg font-semibold text-stone-800 dark:text-stone-200">{title}</h2>
        {count !== undefined && (
          <span className="text-xs bg-stone-200 dark:bg-stone-800 text-stone-600 dark:text-stone-400 px-2 py-0.5 rounded-full">
            {count}
          </span>
        )}
      </div>
      {children}
    </div>
  )
}