import { headers } from "next/headers";
import { storefrontApi } from "@/lib/api";
import { getTemplate } from "@/lib/template";
import { getLocaleFromCookie, getTranslations } from "@/lib/i18n";
import { resolveMediaUrl, getLocalizedText } from "@/lib/utils";
import ProductCard from "@/components/product/ProductCard";
import Link from "next/link";
import Image from "next/image";
import { notFound } from "next/navigation";

export const revalidate = 60;

interface CollectionPageProps {
  params: Promise<{ slug: string }>;
  searchParams: Promise<Record<string, string>>;
}

export default async function CollectionPage({
  params,
  searchParams,
}: CollectionPageProps) {
  const { slug } = await params;
  const sp = await searchParams;

  const headersList = await headers();
  const tenantSlug = headersList.get("x-tenant-slug") || "";
  const cookieHeader = headersList.get("cookie") ?? "";
  const t = getTranslations(getLocaleFromCookie(cookieHeader));

  if (!tenantSlug || tenantSlug === "default") notFound();

  const [configRes, collectionRes] = await Promise.all([
    storefrontApi.getConfig(tenantSlug).catch(() => null),
    storefrontApi.getCollection(tenantSlug, slug, sp).catch(() => null),
  ]);

  if (!collectionRes?.collection) notFound();

  const currency = (configRes?.website as any)?.currency ?? "EGP";
  const templateId = (configRes?.website as any)?.template_id ?? "default";
  const template = getTemplate(templateId);

  const { collection, data: products, meta } = collectionRes;
  const locale = getLocaleFromCookie(cookieHeader);
  const collectionTitle = getLocalizedText(
    collection.title,
    collection.title_ar,
    locale,
  );
  const collectionDescription = getLocalizedText(
    collection.description,
    collection.description_ar,
    locale,
  );
  const bannerUrl = resolveMediaUrl(collection.banner_url);

  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";

  const buildPageUrl = (page: number) => {
    const params = new URLSearchParams({ ...sp, page: String(page) });
    return `/collections/${slug}?${params.toString()}`;
  };

  return (
    <div>
      {/* Banner */}
      {bannerUrl && (
        <div className="relative h-52 sm:h-72 overflow-hidden bg-gray-200">
          <Image
            src={bannerUrl}
            alt={collectionTitle}
            fill
            className="object-cover"
            sizes="100vw"
            priority
          />
          <div className="absolute inset-0 bg-gradient-to-b from-black/20 to-black/55 flex items-end justify-start">
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full pb-10">
              <h1 className="text-3xl sm:text-5xl font-bold text-white mb-2 tracking-tight">
                {collectionTitle}
              </h1>
              {collectionDescription && (
                <p className="text-sm sm:text-base text-white/80 max-w-xl">
                  {collectionDescription}
                </p>
              )}
            </div>
          </div>
        </div>
      )}

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Header (no banner) */}
        {!bannerUrl && (
          <div className="mb-8">
            <nav className="text-xs text-gray-400 mb-4 flex items-center gap-1.5">
              <Link href="/" className="hover:text-gray-600 transition-colors">
                {t.common.home}
              </Link>
              <svg
                className="w-3 h-3 text-gray-300"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={2}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M9 5l7 7-7 7"
                />
              </svg>
              <span className="text-gray-600">{collectionTitle}</span>
            </nav>
            <h1 className="text-2xl font-bold text-gray-900">
              {collectionTitle}
            </h1>
            {collectionDescription && (
              <p className="text-sm text-gray-500 mt-1">
                {collectionDescription}
              </p>
            )}
            <div className="divider-primary mt-3" />
          </div>
        )}

        {/* Filters row */}
        {collection.show_filters && (
          <div className="flex items-center gap-2 mb-6 text-sm text-gray-500">
            <span>
              <strong className="text-gray-900">{meta.total}</strong>{" "}
              {t.collection.products}
            </span>
          </div>
        )}

        {/* Products */}
        {products.length === 0 ? (
          <div className="text-center py-24">
            <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="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"
                />
              </svg>
            </div>
            <p className="text-lg font-semibold text-gray-700 mb-2">
              {t.collection.noProducts}
            </p>
            <Link
              href="/products"
              className="text-sm font-semibold hover:underline"
              style={{ color: "var(--color-primary)" }}
            >
              {t.collection.browseAll}
            </Link>
          </div>
        ) : (
          <>
            <div className={`grid ${colClass} gap-4 md:gap-5`}>
              {products.map((product) => (
                <ProductCard
                  key={product.barcode}
                  product={product}
                  currency={currency}
                  template={template}
                />
              ))}
            </div>

            {/* Pagination */}
            {meta.last_page > 1 && (
              <div className="flex items-center justify-center gap-2 mt-12">
                {meta.current_page > 1 && (
                  <Link
                    href={buildPageUrl(meta.current_page - 1)}
                    className="w-10 h-10 flex items-center justify-center rounded-xl border border-gray-200 text-sm font-medium text-gray-700 hover:bg-gray-50 hover:border-gray-300 transition-all"
                  >
                    <svg
                      className="w-4 h-4"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                      strokeWidth={2}
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        d="M15 19l-7-7 7-7"
                      />
                    </svg>
                  </Link>
                )}
                <span className="text-sm text-gray-500 px-3">
                  {t.collection.page} {meta.current_page} {t.collection.of}{" "}
                  {meta.last_page}
                </span>
                {meta.current_page < meta.last_page && (
                  <Link
                    href={buildPageUrl(meta.current_page + 1)}
                    className="w-10 h-10 flex items-center justify-center rounded-xl border border-gray-200 text-sm font-medium text-gray-700 hover:bg-gray-50 hover:border-gray-300 transition-all"
                  >
                    <svg
                      className="w-4 h-4"
                      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>
    </div>
  );
}
