import { headers } from "next/headers";
import Link from "next/link";
import { storefrontApi } from "@/lib/api";
import { getTemplate } from "@/lib/template";
import { resolveMediaUrl } from "@/lib/utils";
import { getLocaleFromCookie, getTranslations } from "@/lib/i18n";
import ProductCard from "@/components/product/ProductCard";
import HeroSection from "@/components/templates/HeroSection";
import HeroSlider from "@/components/templates/HeroSlider";
import CategorySection from "@/components/templates/CategorySection";
import type { Category, Product, HomeSection } from "@/types";

export const revalidate = 60;

export default async function HomePage() {
  const headersList = await headers();
  const tenantSlug = headersList.get("x-tenant-slug") || "";
  const cookieHeader = headersList.get("cookie") ?? "";
  const locale = getLocaleFromCookie(cookieHeader);
  const t = getTranslations(locale);

  if (!tenantSlug || tenantSlug === "default") {
    return (
      <Unavailable
        reason={`Tenant not resolved from host. Slug received: "${tenantSlug}"`}
        t={t}
      />
    );
  }

  let config: any = null;
  let categories: Category[] = [];
  let newArrivals: Product[] = [];
  let currency = "EGP";
  let configError: string | null = null;

  try {
    const configRes = await storefrontApi.getConfig(tenantSlug);
    config = configRes.website;
    currency = (configRes.website as any).currency ?? "EGP";
  } catch (e: any) {
    configError = e?.message ?? "Unknown error";
  }

  if (configError || !config) {
    return (
      <Unavailable
        reason={configError ?? "No website config returned"}
        slug={tenantSlug}
        t={t}
      />
    );
  }

  try {
    const [catRes, prodRes] = await Promise.all([
      storefrontApi.getCategories(tenantSlug),
      storefrontApi.getProducts(tenantSlug, { per_page: "8", sort: "newest" }),
    ]);
    categories = catRes.categories ?? [];
    newArrivals = prodRes.data ?? [];
  } catch {
    // Catalog failed — still render the hero
  }

  const theme = config?.theme_settings ?? {};
  const hero = {
    ...(theme.hero ?? {}),
    image_url: resolveMediaUrl(theme.hero?.image_url),
  };
  const heroSlides = (theme.hero_slides ?? []).map((slide: any) => ({
    ...slide,
    url: resolveMediaUrl(slide.url) ?? slide.url,
  }));
  const homeSections: HomeSection[] = theme.home_sections ?? [];
  const templateId = (config as any)?.template_id ?? "default";
  const template = getTemplate(templateId);
  const storeName = config?.name ?? "Store";

  const gridCols: Record<string, string> = {
    "grid-2": "grid-cols-2",
    "grid-3": "grid-cols-2 sm:grid-cols-3",
    "grid-4": "grid-cols-2 sm:grid-cols-3 lg:grid-cols-4",
  };
  const colClass =
    gridCols[template.productGrid] ??
    "grid-cols-2 sm:grid-cols-3 lg:grid-cols-4";

  // Fetch products for each enabled home section that has barcodes
  const enabledSections = homeSections.filter(
    (s) => s.enabled && s.barcodes?.length > 0,
  );
  const sectionProducts: Record<string, Product[]> = {};

  await Promise.all(
    enabledSections.map(async (section) => {
      try {
        const res = await storefrontApi.getProducts(tenantSlug, {
          barcodes: section.barcodes.join(","),
          per_page: "12",
        });
        sectionProducts[section.id] = res.data ?? [];
      } catch {
        sectionProducts[section.id] = [];
      }
    }),
  );

  return (
    <div>
      {/* Hero: slider if slides exist, otherwise static hero */}
      {heroSlides.length > 0 ? (
        <HeroSlider slides={heroSlides} storeName={storeName} t={t} />
      ) : (
        <HeroSection
          template={template}
          hero={hero}
          storeName={storeName}
          t={t}
        />
      )}

      <CategorySection categories={categories} template={template} />

      {/* Home sections (featured, top sellers, sale, custom) */}
      {enabledSections.map((section) => {
        const products = sectionProducts[section.id] ?? [];
        if (products.length === 0) return null;
        return (
          <section
            key={section.id}
            className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16 lg:py-20"
          >
            <div className="flex items-end justify-between mb-8">
              <div>
                <h2 className="text-2xl font-bold text-gray-900">
                  {section.title}
                </h2>
                <div className="divider-primary mt-2" />
              </div>
              <Link
                href="/products"
                className="text-sm font-medium text-gray-500 hover:text-gray-900 transition-colors flex items-center gap-1 group pb-0.5"
              >
                {t.home.viewAll}
                <svg
                  className="w-4 h-4 transition-transform group-hover:translate-x-0.5"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  strokeWidth={2}
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M9 5l7 7-7 7"
                  />
                </svg>
              </Link>
            </div>
            <div className={`grid ${colClass} gap-4 md:gap-5`}>
              {products.map((p) => (
                <ProductCard
                  key={p.id}
                  product={p}
                  currency={currency}
                  template={template}
                />
              ))}
            </div>
          </section>
        );
      })}

      {/* New Arrivals (shown when no custom sections are configured) */}
      {enabledSections.length === 0 && newArrivals.length > 0 && (
        <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16 lg:py-20">
          <div className="flex items-end justify-between mb-8">
            <div>
              <h2 className="text-2xl font-bold text-gray-900">
                {t.home.newArrivals}
              </h2>
              <div className="divider-primary mt-2" />
            </div>
            <Link
              href="/products"
              className="text-sm font-medium text-gray-500 hover:text-gray-900 transition-colors flex items-center gap-1 group pb-0.5"
            >
              {t.home.viewAll}
              <svg
                className="w-4 h-4 transition-transform group-hover:translate-x-0.5"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={2}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M9 5l7 7-7 7"
                />
              </svg>
            </Link>
          </div>
          <div className={`grid ${colClass} gap-4 md:gap-5`}>
            {newArrivals.map((p) => (
              <ProductCard
                key={p.id}
                product={p}
                currency={currency}
                template={template}
              />
            ))}
          </div>
        </section>
      )}
    </div>
  );
}

function Unavailable({
  reason,
  slug,
  t,
}: {
  reason?: string;
  slug?: string;
  t: import("@/lib/i18n").Translations;
}) {
  const isDev = process.env.NODE_ENV !== "production";
  return (
    <div className="flex items-center justify-center min-h-[60vh]">
      <div className="text-center px-4 max-w-lg">
        <div className="w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-5">
          <svg
            className="w-8 h-8 text-gray-400"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={1.5}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M13.5 21v-7.5a.75.75 0 01.75-.75h3a.75.75 0 01.75.75V21m-4.5 0H2.36m11.14 0H18m0 0h3.64m-1.39 0V9.349m-16.5 11.65V9.35m0 0a3.001 3.001 0 003.75-.615A2.993 2.993 0 009.75 9.75c.896 0 1.7-.393 2.25-1.016a2.993 2.993 0 002.25 1.016c.896 0 1.7-.393 2.25-1.016a3.001 3.001 0 003.75.614m-16.5 0a3.004 3.004 0 01-.621-4.72L4.318 3.44A1.5 1.5 0 015.378 3h13.243a1.5 1.5 0 011.06.44l1.19 1.189a3 3 0 01-.621 4.72m-13.5 8.65h3.75a.75.75 0 00.75-.75V13.5a.75.75 0 00-.75-.75H6.75a.75.75 0 00-.75.75v3.75c0 .415.336.75.75.75z"
            />
          </svg>
        </div>
        <h1 className="text-2xl font-bold text-gray-900 mb-2">
          {t.common.storeUnavailable}
        </h1>
        <p className="text-gray-500 mb-4">{t.common.storeUnavailableHint}</p>
        {(isDev || slug) && reason && (
          <details className="mt-4 text-left bg-amber-50 border border-amber-200 rounded-xl p-4">
            <summary className="text-xs font-semibold text-amber-700 cursor-pointer">
              {t.common.debugInfo}
            </summary>
            <pre className="mt-2 text-xs text-amber-800 whitespace-pre-wrap break-all">
              {slug ? `Tenant slug: ${slug}\n` : ""}
              {`LARAVEL_API_URL: ${
                process.env.LARAVEL_API_URL ?? "(not set)"
              }\n`}
              {`APP_DOMAIN: ${
                process.env.NEXT_PUBLIC_APP_DOMAIN ?? "(not set)"
              }\n`}
              {`Error: ${reason}`}
            </pre>
          </details>
        )}
      </div>
    </div>
  );
}
