import type { Metadata } from "next";
import Link from "next/link";
import { PackageCheck, Search, ShieldCheck } from "lucide-react";
import { ProductCard } from "@/components/ProductCard";
import { ProductFilterPanel } from "@/components/ProductFilterPanel";
import { prisma } from "@/lib/prisma";
import { displayPrice } from "@/lib/utils";

export const metadata: Metadata = {
  title: "Gold & Silver Bullion Products | ELIT GOLD",
  description: "Browse physical gold and silver bullion products including bars, coins, rounds, IRA-eligible options, and manually updated pricing."
};

const categoryChips = [
  { label: "All Products", href: "/products" },
  { label: "Gram Gold", href: "/products?search=Gram%20Gold", search: "Gram Gold" },
  { label: "Gold Bars", href: "/products?metal=GOLD&type=BAR", metal: "GOLD", type: "BAR" },
  { label: "Gold Coins", href: "/products?metal=GOLD&type=COIN", metal: "GOLD", type: "COIN" },
  { label: "Silver Bars", href: "/products?metal=SILVER&type=BAR", metal: "SILVER", type: "BAR" },
  { label: "Silver Coins", href: "/products?metal=SILVER&type=COIN", metal: "SILVER", type: "COIN" },
  { label: "IRA Eligible", href: "/products?ira=true", ira: true },
  { label: "PAMP Suisse", href: "/products?search=PAMP%20Suisse", search: "PAMP Suisse" },
  { label: "Valcambi", href: "/products?search=Valcambi", search: "Valcambi" },
  { label: "Royal Mint", href: "/products?search=Royal%20Mint", search: "Royal Mint" }
];

export default async function ProductsPage({ searchParams }: { searchParams: Record<string, string | undefined> }) {
  const search = searchParams.search || searchParams.q || "";
  const metal = searchParams.metal?.toUpperCase();
  const type = searchParams.type?.toUpperCase();
  let products: Awaited<ReturnType<typeof prisma.product.findMany>> = [];
  let productLoadFailed = false;

  try {
    products = await prisma.product.findMany({
      where: {
        AND: [
          { itemKind: "PHYSICAL_BULLION", isPublicProduct: true },
          metal ? { metalType: metal } : {},
          type ? { productType: type } : {},
          search ? {
            OR: [
              { name: { contains: search } },
              { brandMint: { contains: search } },
              { mintBrand: { contains: search } },
              { metalType: { contains: search.toUpperCase() } },
              { weight: { contains: search } },
              { purity: { contains: search } }
            ]
          } : {},
          searchParams.ira === "true" ? { isIraEligible: true } : {}
        ]
      },
      orderBy: [{ isFeatured: "desc" }, { stockStatus: "asc" }, { createdAt: "desc" }]
    });
  } catch {
    productLoadFailed = true;
  }

  const sorted = [...products].sort((a, b) => {
    if (searchParams.sort === "price-desc") return displayPrice(b) - displayPrice(a);
    if (searchParams.sort === "price-asc") return displayPrice(a) - displayPrice(b);
    if (b.isFeatured !== a.isFeatured) return Number(b.isFeatured) - Number(a.isFeatured);
    if (a.stockStatus !== b.stockStatus) return a.stockStatus === "IN_STOCK" ? -1 : 1;
    return 0;
  });
  const title = metal === "GOLD" ? "Gold Bullion Products" : metal === "SILVER" ? "Silver Bullion Products" : "Gold & Silver Bullion Products";
  const activeFilters = [
    search ? `Search: ${search}` : "",
    metal ? `Metal: ${metal}` : "",
    type ? `Type: ${type}` : "",
    searchParams.ira === "true" ? "IRA Eligible" : ""
  ].filter(Boolean);
  const hasCatalogFilter = Boolean(search || metal || type || searchParams.ira === "true");

  function isChipActive(chip: typeof categoryChips[number]) {
    if (chip.label === "All Products") return !hasCatalogFilter;
    if (chip.search) return search === chip.search;
    if (chip.ira) return searchParams.ira === "true";
    return (!chip.metal || metal === chip.metal) && (!chip.type || type === chip.type);
  }

  return (
    <section className="storefront-page products-listing-page products-catalog-page relative">
      <div className="products-listing-bg" />
      <div className="container-grid relative py-4 md:py-5">
        <div className="listing-category-panel products-catalog-header">
          <div className="listing-corner-mark" />
          <div className="relative text-xs font-black uppercase tracking-[0.14em] text-[#5f5a52]">
            <Link href="/" className="hover:text-[#7a5310]">Home</Link>
            <span className="px-2 text-[#b58b24]">/</span>
            <span className="text-[#171717]">Products</span>
          </div>
          <div className="relative mt-3 grid gap-4 lg:grid-cols-[minmax(0,1fr)_390px] lg:items-end">
            <div>
              <p className="section-kicker">Physical bullion catalog</p>
              <h1 className="mt-2 text-3xl font-black leading-tight text-[#171717] md:text-4xl">{title}</h1>
              <p className="mt-3 max-w-3xl text-sm leading-6 text-[#5f5a52] md:text-base">Browse physical gold and silver bullion with compact filters for metal, format, weight, purity, mint, availability, and IRA eligibility.</p>
            </div>
            <form className="listing-search-panel">
              <div className="listing-search-field">
                <Search size={17} className="text-[#b58b24]" />
                <input className="min-w-0 border-0 bg-transparent p-0 shadow-none outline-none focus-visible:outline-0" name="search" defaultValue={search} placeholder="Search products, mints, weights" />
              </div>
              <button className="btn btn-primary whitespace-nowrap">Search</button>
            </form>
          </div>

          <div className="listing-chip-row">
            {categoryChips.map((chip) => {
              const active = isChipActive(chip);
              return (
              <Link
                key={chip.label}
                href={active && chip.label !== "All Products" ? "/products" : chip.href}
                className={`listing-category-chip ${
                  active ? "listing-category-chip-active" : ""
                }`}
                aria-current={active ? "page" : undefined}
              >
                {chip.label}
              </Link>
              );
            })}
          </div>
        </div>

        <div className="products-catalog-layout mt-4 grid gap-4 lg:grid-cols-[270px_minmax(0,1fr)]">
          <ProductFilterPanel search={search} sort={searchParams.sort} resultCount={sorted.length} />

          <div className="min-w-0">
            <div className="catalog-trust-row">
              <span><ShieldCheck size={16} /> Secure Checkout</span>
              <span><PackageCheck size={16} /> Manual Pricing</span>
              <span><Search size={16} /> Product Detail Review</span>
            </div>
            <div className="listing-results-shell products-results-toolbar">
              <div className="listing-toolbar">
                <div>
                  <p className="text-xs font-black uppercase tracking-[0.14em] text-[#7a5310]">Results</p>
                  <div className="mt-1 font-black text-[#171717]">{sorted.length} physical bullion products</div>
                </div>
                <form className="grid w-full gap-2 sm:w-auto sm:grid-cols-[auto_190px_auto] sm:items-center">
                  <input type="hidden" name="search" value={search} />
                  <label className="flex-row items-center gap-2 text-xs font-black uppercase tracking-[0.12em] text-[#5f5a52] sm:flex">Sort</label>
                  <select className="min-h-10 rounded border-[#d8c98f] bg-white text-sm font-bold" name="sort" defaultValue={searchParams.sort || "featured"}>
                    <option value="featured">Featured</option>
                    <option value="price-asc">Price Low to High</option>
                    <option value="price-desc">Price High to Low</option>
                  </select>
                  <button className="btn btn-secondary min-h-10">Apply Sort</button>
                </form>
              </div>
              {activeFilters.length ? (
                <div className="listing-active-filters">
                  {activeFilters.map((filter) => (
                    <span key={filter} className="rounded-full border border-[#d4af37] bg-[#fffaf0] px-3 py-1.5 text-xs font-black text-[#7a5310] shadow-sm">
                      {filter}
                    </span>
                  ))}
                  <Link href="/products" className="rounded-full border border-[#e2d8c5] bg-white px-3 py-1.5 text-xs font-black text-[#171717] transition hover:border-[#d4af37] hover:bg-[#fffaf0]">
                    Clear all
                  </Link>
                </div>
              ) : null}
            </div>
            {productLoadFailed ? (
              <div className="listing-empty-card">
                <h2 className="text-xl font-black text-[#171717]">Products are temporarily unavailable</h2>
                <p className="mt-2">Please check back shortly or contact support for current bullion availability.</p>
                <div className="mt-5 flex flex-wrap justify-center gap-2">
                  <Link href="/products" className="btn btn-primary">View All Products</Link>
                  <Link href="/contact" className="btn btn-secondary">Contact Support</Link>
                </div>
              </div>
            ) : sorted.length ? (
              <div className="listing-grid-surface products-grid-shell">
                <div className="grid min-w-0 gap-3 sm:grid-cols-2 xl:grid-cols-4">
                  {sorted.map((product) => <ProductCard key={product.id} product={product} />)}
                </div>
              </div>
            ) : (
              <div className="listing-empty-card">
                <h2 className="text-xl font-black text-[#171717]">No products found</h2>
                <p className="mx-auto mt-2 max-w-xl">Try a different metal, mint, weight, or product type to continue browsing physical bullion products.</p>
                <div className="mt-5 flex flex-wrap justify-center gap-2">
                  <Link href="/products" className="btn btn-primary">Clear Filters</Link>
                  <Link href="/products" className="btn btn-secondary">View All Products</Link>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}
