import { headers } from "next/headers";
import { storefrontApi } from "@/lib/api";
import { getTemplate } from "@/lib/template";
import ProductCard from "@/components/product/ProductCard";
import Link from "next/link";

export const revalidate = 120;

export default async function CategoryPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ page?: string; sort?: string }>;
}) {
  const headersList = await headers();
  const tenantSlug = headersList.get("x-tenant-slug") || "default";
  const { id } = await params;
  const sp = await searchParams;

  const filterParams: Record<string, string> = { category_id: id };
  if (sp.page) filterParams.page = sp.page;
  if (sp.sort) filterParams.sort = sp.sort;

  const [productsRes, configRes] = await Promise.all([
    storefrontApi.getProducts(tenantSlug, filterParams).catch(() => ({
      data: [],
      meta: { current_page: 1, last_page: 1, per_page: 20, total: 0 },
      links: {},
    })),
    storefrontApi.getConfig(tenantSlug).catch(() => null),
  ]);

  const products = productsRes.data ?? [];
  const meta = productsRes.meta;
  const currency = (configRes?.website as any)?.currency ?? "EGP";
  const templateId = (configRes?.website as any)?.template_id ?? "default";
  const template = getTemplate(templateId);

  const buildUrl = (page: number) => {
    const qs = new URLSearchParams({
      ...filterParams,
      page: String(page),
    }).toString();
    return `/categories/${id}?${qs}`;
  };

  const sortOptions = [
    { label: "Newest", value: "newest" },
    { label: "Price: Low → High", value: "price_asc" },
    { label: "Price: High → Low", value: "price_desc" },
  ];

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <nav className="text-xs text-gray-400 mb-6 flex items-center gap-1.5">
        <Link href="/" className="hover:text-gray-600 transition-colors">
          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>
        <Link
          href="/categories"
          className="hover:text-gray-600 transition-colors"
        >
          Categories
        </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">Category</span>
      </nav>

      <div className="flex items-end justify-between mb-8">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">
            {meta.total} {meta.total === 1 ? "Product" : "Products"}
          </h1>
          <div className="divider-primary mt-2" />
        </div>
        <div className="flex items-center gap-2">
          {sortOptions.map((opt) => (
            <Link
              key={opt.value}
              href={`/categories/${id}?sort=${opt.value}`}
              className={`text-xs font-medium px-3 py-1.5 rounded-lg border transition-all ${
                sp.sort === opt.value
                  ? "border-gray-900 bg-gray-900 text-white"
                  : "border-gray-200 text-gray-600 hover:border-gray-400"
              }`}
            >
              {opt.label}
            </Link>
          ))}
        </div>
      </div>

      {products.length === 0 ? (
        <div className="text-center py-24 bg-white rounded-2xl border border-gray-100">
          <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-base font-semibold text-gray-700 mb-1">
            No products in this category yet
          </p>
          <Link
            href="/products"
            className="mt-4 inline-block text-sm font-semibold hover:underline"
            style={{ color: "var(--color-primary)" }}
          >
            Browse all products
          </Link>
        </div>
      ) : (
        <div
          className={`grid gap-4 md:gap-5 ${
            template.productGrid === "grid-3"
              ? "grid-cols-2 sm:grid-cols-3"
              : template.productGrid === "grid-2"
              ? "grid-cols-2"
              : "grid-cols-2 sm:grid-cols-3 lg:grid-cols-4"
          }`}
        >
          {products.map((p) => (
            <ProductCard
              key={p.id}
              product={p}
              currency={currency}
              template={template}
            />
          ))}
        </div>
      )}

      {meta.last_page > 1 && (
        <div className="flex items-center justify-center gap-2 mt-12">
          {meta.current_page > 1 && (
            <Link
              href={buildUrl(meta.current_page - 1)}
              className="w-10 h-10 flex items-center justify-center rounded-xl border border-gray-200 text-sm font-medium 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">
            Page {meta.current_page} / {meta.last_page}
          </span>
          {meta.current_page < meta.last_page && (
            <Link
              href={buildUrl(meta.current_page + 1)}
              className="w-10 h-10 flex items-center justify-center rounded-xl border border-gray-200 text-sm font-medium 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>
  );
}
