import type { Metadata } from "next";
import PaginatedBookList from "@/components/web/books/PaginatedBookList";
import SearchBar from "@/components/web/SearchBar";
import { searchBooks } from "@/lib/data";
import Image from "next/image";

export const metadata: Metadata = {
  title: "Home | E-Library",
  description: "Browse and search the Federal Polytechnic Bali E-Library collection.",
};

export default async function Home({
  searchParams,
}: {
  searchParams: Promise<{ q?: string }>;
}) {
  const { q } = await searchParams;
  const results = await searchBooks(q ?? "");
  const hasQuery = !!q?.trim();

  return(
    <main className="flex flex-col w-full items-center">
      <div className="bg-primary w-full flex flex-col items-center justify-center h-[50vh]">
        <div className="flex flex-col justify-center items-center text-primary-foreground gap-0">
          <Image 
            src="/fub_logo.png"
            width={400}
            height={100}
            alt="Logo"
            loading="eager"
            style={{ height: "auto" }}
          />
          <h1 className="text-primary-foreground text-2xl font-semibold">E-Library</h1>
        </div>
        <SearchBar />
      </div>

      {/* Results meta */}
      <section className="w-full"> 
        <p className="text-[0.78rem] uppercase tracking-wider mt-6 text-muted-foreground text-center">
          {hasQuery ? (
            <>
              <strong className="font-bold">{results.length}</strong>
              {" "}result{results.length !== 1 ? "s" : ""} for{" "}
              <span className="font-bold">&ldquo;{q}&rdquo;</span>
            </>
          ) : (
            <>
              All books &mdash;{" "}
              <strong className="font-bold">{results.length}</strong> items
            </>
          )}
        </p>

        {/* Empty state */}
        {results.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-24 gap-4 text-secondary">
            <span className="text-5xl text-muted leading-none">⌕</span>
            <p className="text-sm tracking-wider">Nothing matched. Try a different term.</p>
          </div>
        ) : (
          /* Book Grid */
          <PaginatedBookList books={results} />
        )}
      </section>
    </main>
  )
}
