import Image from "next/image";
import Link from "next/link";
import { ArrowRight, MessageSquareQuote } from "lucide-react";
import ProductTileImage from "@/components/ui/ProductTileImage";
import { catalogApi } from "@/lib/api/catalog";
import type { ApiCategory, ApiProduct } from "@/lib/api/types";
import { HOME_IMAGES, imageForProduct } from "@/lib/home/images";
import ProductRail, { type RailProduct } from "./ProductRail";
import Reveal from "./Reveal";

/**
 * Stocked categories and the catalogue behind them. Cached for 2 minutes so
 * the homepage stays statically renderable.
 */
async function fetchCatalog(): Promise<{ categories: ApiCategory[]; products: ApiProduct[] }> {
  const [categories, products] = await Promise.all([
    catalogApi
      .categories({ per_page: 12, with_products: true }, { next: { revalidate: 120 } })
      .then((r) => r.data)
      .catch(() => [] as ApiCategory[]),
    catalogApi
      .products({ per_page: 50, with_price: true }, { next: { revalidate: 120 } })
      .then((r) => r.data)
      .catch(() => [] as ApiProduct[]),
  ]);
  return { categories, products };
}

/** A photo of the goods in a category, for when it has no working banner of its own. */
function categoryFallback(cat: ApiCategory, index: number): string {
  const byName = imageForProduct(cat.name, "");
  if (byName) return byName;
  return [HOME_IMAGES.coils, HOME_IMAGES.billets, HOME_IMAGES.structural][index % 3];
}

export default async function CategoriesSection() {
  const { categories, products } = await fetchCatalog();

  const byCategory = new Map<number, ApiProduct[]>();
  for (const p of products) {
    const id = p.category?.id;
    if (!id) continue;
    byCategory.set(id, [...(byCategory.get(id) ?? []), p]);
  }
  const shown = categories.filter((c) => (byCategory.get(c.id)?.length ?? 0) > 0).slice(0, 5);

  const rail: RailProduct[] = products.slice(0, 12).map((p) => ({
    id: p.id,
    name: p.name,
    href: `/products/${p.slug || p.id}`,
    image: p.thumbnail || p.images?.[0] || null,
    fallbackImage: imageForProduct(`${p.name} ${p.sub_category?.name ?? ""}`),
    category: p.category?.name ?? null,
    subCategory: p.sub_category?.name ?? null,
    unit: p.unit?.name ?? null,
    // "from ₹X/MT" (4.10): the cheapest live ex-works offer a seller publishes.
    fromPrice: p.from_price?.ex_works ?? null,
  }));

  return (
    <section className="bg-slate-50 pb-16 pt-20 sm:pb-20 sm:pt-24">
      <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
        <Reveal className="max-w-2xl">
          <span className="text-sm font-semibold uppercase tracking-wider text-[#CC1414]">Explore categories</span>
          <h2 className="mt-2 text-3xl font-black tracking-tight text-slate-900 md:text-4xl">
            Steel &amp; other commodities, sourced right
          </h2>
          <p className="mt-3 text-slate-500">
            Compare live offers from verified mills and dealers, then book at the best F.O.R price for your city.
          </p>
        </Reveal>

        {shown.length > 0 ? (
          <div className={`mt-10 grid gap-5 ${shown.length === 1 ? "md:grid-cols-2" : "md:grid-cols-2 lg:grid-cols-3"}`}>
            {shown.map((cat, i) => {
              const items = byCategory.get(cat.id) ?? [];
              return (
                <Reveal key={cat.id} delay={i * 90}>
                  <Link
                    href={`/categories/${cat.slug}`}
                    className="group relative flex h-full min-h-[340px] flex-col justify-end overflow-hidden rounded-3xl bg-slate-900 p-6 text-white shadow-lg"
                  >
                    <ProductTileImage
                      src={cat.banner || cat.thumbnail}
                      fallbackSrc={categoryFallback(cat, i)}
                      fit="cover"
                      alt=""
                      sizes="(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 420px"
                      className="transition-transform duration-700 group-hover:scale-110"
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-slate-950 via-slate-950/60 to-slate-950/5" />
                    <div className="relative">
                      <span className="inline-flex rounded-full bg-white/15 px-2.5 py-1 text-[11px] font-semibold backdrop-blur">
                        {items.length} product{items.length === 1 ? "" : "s"}
                      </span>
                      <h3 className="mt-3 text-2xl font-extrabold capitalize tracking-tight">
                        {cat.name.toLowerCase()}
                      </h3>
                      <p className="mt-1 line-clamp-2 text-sm text-white/70">
                        {cat.meta?.description || `Best live prices on ${cat.name.toLowerCase()} steel from verified sellers.`}
                      </p>
                      <ul className="mt-4 flex flex-wrap gap-1.5">
                        {items.slice(0, 6).map((p) => (
                          <li
                            key={p.id}
                            className="rounded-full border border-white/20 bg-white/10 px-2.5 py-1 text-[11px] font-medium text-white/90 backdrop-blur"
                          >
                            {p.name}
                          </li>
                        ))}
                        {items.length > 6 ? (
                          <li className="rounded-full px-2 py-1 text-[11px] font-medium text-white/70">
                            +{items.length - 6} more
                          </li>
                        ) : null}
                      </ul>
                      <span className="mt-5 inline-flex items-center gap-1.5 text-sm font-semibold text-white">
                        Explore {cat.name.toLowerCase()}
                        <ArrowRight size={16} className="transition-transform group-hover:translate-x-1" aria-hidden />
                      </span>
                    </div>
                  </Link>
                </Reveal>
              );
            })}

            {/* Always offer a way in for goods that aren't listed yet. */}
            <Reveal
              delay={shown.length * 90}
              // An odd tile count leaves this one alone on the two-up tablet row: let it fill the row.
              className={(shown.length + 1) % 2 === 1 ? "md:col-span-2 lg:col-span-1" : undefined}
            >
              <Link
                href="#get-quote"
                className="group relative flex h-full min-h-[340px] flex-col justify-end overflow-hidden rounded-3xl bg-[#CC1414] p-6 text-white shadow-lg"
              >
                <Image
                  src={HOME_IMAGES.construction}
                  alt=""
                  fill
                  sizes="(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 420px"
                  className="object-cover opacity-35 mix-blend-luminosity transition-transform duration-700 group-hover:scale-110"
                />
                <div className="absolute inset-0 bg-gradient-to-t from-[#8f0d0d] via-[#CC1414]/70 to-[#CC1414]/20" />
                <div className="relative">
                  <span className="flex h-11 w-11 items-center justify-center rounded-2xl bg-white/15 backdrop-blur">
                    <MessageSquareQuote size={22} aria-hidden />
                  </span>
                  <h3 className="mt-4 text-2xl font-extrabold tracking-tight">Need something else?</h3>
                  <p className="mt-1 text-sm text-white/80">
                    Aluminium, copper, cement, polymers, chemicals — tell us the grade and quantity and we&apos;ll source it.
                  </p>
                  <span className="mt-5 inline-flex items-center gap-1.5 rounded-xl bg-white px-4 py-2.5 text-sm font-semibold text-[#CC1414]">
                    Post your requirement
                    <ArrowRight size={16} className="transition-transform group-hover:translate-x-1" aria-hidden />
                  </span>
                </div>
              </Link>
            </Reveal>
          </div>
        ) : null}

        {rail.length > 0 ? (
          <div className="mt-16">
            <div className="mb-6 flex items-end justify-between gap-4">
              <div>
                <h3 className="text-2xl font-black tracking-tight text-slate-900">Popular products</h3>
                <p className="mt-1 text-sm text-slate-500">Tap a product to see live offers near you.</p>
              </div>
              <Link
                href="/products"
                className="shrink-0 text-sm font-semibold text-[#CC1414] hover:underline sm:mr-28"
              >
                View all →
              </Link>
            </div>
            <ProductRail products={rail} />
          </div>
        ) : null}
      </div>
    </section>
  );
}
