import Link from "next/link";
import Image from "next/image";
import type { ReactNode } from "react";
import type { Metadata } from "next";
import { prisma } from "@/lib/prisma";
import ProductCard from "@/components/ProductCard";
import HeroSlider, { type HeroSlide } from "@/components/HeroSlider";
import { parseImages } from "@/lib/types";
import { SITE } from "@/lib/site";

export async function generateMetadata(): Promise<Metadata> {
  const page = await prisma.pageSeo.findUnique({ where: { path: "/" } });
  if (!page?.title && !page?.description) return {};
  return { title: page?.title || undefined, description: page?.description || undefined };
}

async function getBestSellers(limit: number) {
  const items = await prisma.orderItem.findMany({ where: { order: { status: "paid" } }, select: { productId: true, quantity: true } });
  const unitsByProduct = new Map<string, number>();
  for (const item of items) {
    unitsByProduct.set(item.productId, (unitsByProduct.get(item.productId) ?? 0) + item.quantity);
  }
  const topProductIds = [...unitsByProduct.entries()]
    .sort((a, b) => b[1] - a[1])
    .slice(0, limit)
    .map(([id]) => id);
  if (topProductIds.length === 0) return [];

  const products = await prisma.product.findMany({
    where: { id: { in: topProductIds }, active: true },
    include: { category: true, variants: true },
  });
  const order = new Map(topProductIds.map((id, i) => [id, i]));
  return products.sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0));
}

export default async function HomePage() {
  const [sections, categories, collections, banners] = await Promise.all([
    prisma.homepageSection.findMany({ where: { active: true }, orderBy: { sortOrder: "asc" } }),
    prisma.category.findMany({
      where: { products: { some: { active: true } } },
      orderBy: { name: "asc" },
      include: { products: { where: { active: true }, take: 1, orderBy: { createdAt: "desc" }, select: { images: true } } },
    }),
    prisma.collection.findMany({
      include: { products: { where: { active: true }, include: { category: true, variants: true }, take: 4 } },
      orderBy: { createdAt: "asc" },
    }),
    prisma.banner.findMany({ where: { active: true }, orderBy: { sortOrder: "asc" } }),
  ]);
  const nonEmptyCollections = collections.filter((c) => c.products.length > 0);
  const sectionMap = new Map(sections.map((s) => [s.key, s]));
  const toSlide = (b: (typeof banners)[number]): HeroSlide => ({ src: b.image, alt: b.title ?? SITE.name });
  const desktopSlides = banners.filter((b) => b.device !== "mobile").map(toSlide);
  const mobileSlides = banners.filter((b) => b.device !== "desktop").map(toSlide);

  const [featuredProducts, newArrivals, bestSellers, flashSale] = await Promise.all([
    sectionMap.has("featured")
      ? prisma.product.findMany({
          where: { active: true, featured: true },
          include: { category: true, variants: true },
          orderBy: { createdAt: "desc" },
          take: sectionMap.get("featured")!.itemLimit,
        })
      : Promise.resolve([]),
    sectionMap.has("new_arrivals")
      ? prisma.product.findMany({
          where: { active: true },
          include: { category: true, variants: true },
          orderBy: { createdAt: "desc" },
          take: sectionMap.get("new_arrivals")!.itemLimit,
        })
      : Promise.resolve([]),
    sectionMap.has("best_sellers") ? getBestSellers(sectionMap.get("best_sellers")!.itemLimit) : Promise.resolve([]),
    prisma.festivalOffer.findFirst({
      where: { showOnHomepage: true, active: true, startsAt: { lte: new Date() }, endsAt: { gte: new Date() } },
    }),
  ]);

  const sectionBlocks: Record<string, ReactNode> = {
    categories: categories.length > 0 && (
      <section key="categories" className="mx-auto max-w-7xl px-4 py-12 sm:px-6">
        <h2 className="font-[family-name:var(--font-heading)] text-xl font-bold text-rose-800 sm:text-2xl">
          Explore Our Categories
        </h2>
        <span className="mt-2 block h-0.5 w-12 bg-gold-400" />
        <div className="mt-5 grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6">
          {categories.map((c) => {
            const image = parseImages(c.products[0]?.images ?? "[]")[0];
            return (
              <Link key={c.id} href={`/shop?category=${c.slug}`} className="block">
                <div className="relative aspect-square overflow-hidden rounded-xl bg-rose-50">
                  <Image
                    src={image}
                    alt={c.name}
                    fill
                    className="object-cover"
                    sizes="(max-width: 640px) 50vw, (max-width: 768px) 33vw, (max-width: 1024px) 25vw, 16vw"
                  />
                </div>
                <p className="mt-2 text-center text-sm font-semibold text-rose-800">{c.name}</p>
              </Link>
            );
          })}
        </div>
      </section>
    ),
    collections:
      nonEmptyCollections.length > 0 && (
        <div key="collections">
          {nonEmptyCollections.map((c) => (
            <section key={c.id} className="mx-auto max-w-7xl px-4 py-12 sm:px-6">
              <div className="flex items-start justify-between">
                <div>
                  <h2 className="font-[family-name:var(--font-heading)] text-xl font-semibold text-stone-800">{c.name}</h2>
                  <span className="mt-2 block h-0.5 w-12 bg-gold-400" />
                </div>
                <Link href={`/shop?collection=${c.slug}`} className="text-sm font-medium text-rose-700 hover:underline">
                  See all
                </Link>
              </div>
              <div className="mt-5 grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
                {c.products.map((p) => (
                  <ProductCard key={p.id} product={p} />
                ))}
              </div>
            </section>
          ))}
        </div>
      ),
    featured: featuredProducts.length > 0 && (
      <section key="featured" className="mx-auto max-w-7xl px-4 py-12 sm:px-6">
        <h2 className="font-[family-name:var(--font-heading)] text-xl font-semibold text-stone-800">Featured</h2>
        <span className="mt-2 block h-0.5 w-12 bg-gold-400" />
        <div className="mt-5 grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
          {featuredProducts.map((p) => (
            <ProductCard key={p.id} product={p} />
          ))}
        </div>
      </section>
    ),
    best_sellers: bestSellers.length > 0 && (
      <section key="best_sellers" className="mx-auto max-w-7xl px-4 py-12 sm:px-6">
        <h2 className="font-[family-name:var(--font-heading)] text-xl font-semibold text-stone-800">Best sellers</h2>
        <span className="mt-2 block h-0.5 w-12 bg-gold-400" />
        <div className="mt-5 grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
          {bestSellers.map((p) => (
            <ProductCard key={p.id} product={p} />
          ))}
        </div>
      </section>
    ),
    flash_sale: flashSale && (
      <section key="flash_sale" className="mx-auto max-w-7xl px-4 pt-12 sm:px-6">
        <div className="rounded-xl bg-gradient-to-r from-rose-700 to-rose-600 px-6 py-5 text-center text-white">
          <p className="text-lg font-bold">⚡ {flashSale.name} — {flashSale.discountPercent}% off</p>
          <p className="mt-1 text-sm text-rose-100">Ends {flashSale.endsAt.toLocaleDateString("en-IN", { day: "numeric", month: "short" })}</p>
          <Link href="/shop" className="mt-3 inline-block rounded-md bg-white px-5 py-2 text-sm font-semibold text-rose-700 hover:bg-rose-50">
            Shop the sale
          </Link>
        </div>
      </section>
    ),
    new_arrivals: (
      <section key="new_arrivals" className="mx-auto max-w-7xl px-4 py-12 sm:px-6">
        <div className="flex items-start justify-between">
          <div>
            <h2 className="font-[family-name:var(--font-heading)] text-xl font-semibold text-stone-800">New arrivals</h2>
            <span className="mt-2 block h-0.5 w-12 bg-gold-400" />
          </div>
          <Link href="/shop" className="text-sm font-medium text-rose-700 hover:underline">
            View all
          </Link>
        </div>
        {newArrivals.length === 0 ? (
          <p className="mt-6 text-sm text-stone-500">
            No products yet — add some from the{" "}
            <Link href="/iv-manage-84x2" className="text-rose-700 underline">
              admin panel
            </Link>
            .
          </p>
        ) : (
          <div className="mt-5 grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
            {newArrivals.map((p) => (
              <ProductCard key={p.id} product={p} />
            ))}
          </div>
        )}
      </section>
    ),
  };

  return (
    <div>
      <section className="bg-gradient-to-b from-amber-50 to-rose-50/40">
        <div className="border-y-2 border-gold-400">
          {/* Only one of these two is ever visible per breakpoint; `eager` (preload) is deliberately
              limited to the mobile version since this store's traffic skews mobile-heavy — marking
              both eager would preload both image sets on every visit regardless of device. */}
          {mobileSlides.length > 0 && (
            <div className="sm:hidden">
              <HeroSlider slides={mobileSlides} aspectRatio="941 / 557" eager />
            </div>
          )}
          {desktopSlides.length > 0 && (
            <div className="hidden sm:block">
              <HeroSlider slides={desktopSlides} aspectRatio="1774 / 887" />
            </div>
          )}
        </div>
        <div className="mx-auto hidden max-w-7xl px-4 py-8 text-center sm:block sm:px-6">
          <div className="flex flex-wrap justify-center gap-2">
            <span className="inline-block rounded-full bg-white px-3 py-1 text-xs font-semibold text-rose-700 shadow-sm">
              Handpicked return gifts, made memorable
            </span>
            {SITE.googleProfileUrl && (
              <a
                href={SITE.googleProfileUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center gap-1 rounded-full bg-white px-3 py-1 text-xs font-semibold text-rose-700 shadow-sm hover:bg-rose-50"
              >
                <span className="text-gold-400">★★★★★</span> {SITE.googleReviewCount} Google reviews
              </a>
            )}
          </div>
          <div className="mt-6 flex flex-wrap justify-center gap-3">
            <Link href="/shop" className="rounded-md bg-rose-700 px-6 py-3 text-sm font-semibold text-white hover:bg-rose-800">
              Shop all gifts
            </Link>
            <Link
              href="/shop?category=corporate-bulk-gifts"
              className="rounded-md border border-rose-200 bg-white px-6 py-3 text-sm font-semibold text-rose-800 hover:bg-rose-50"
            >
              Bulk &amp; corporate orders
            </Link>
          </div>
        </div>
      </section>

      {sections.map((s) => sectionBlocks[s.key] ?? null)}
    </div>
  );
}
