import { headers } from "next/headers";
import { storefrontApi } from "@/lib/api";
import { getTemplate } from "@/lib/template";
import { getLocaleFromCookie, getTranslations } from "@/lib/i18n";
import ProductCard from "@/components/product/ProductCard";
import PriceRangeSlider from "@/components/ui/PriceRangeSlider";
import FilterColorLink from "@/app/products/FilterColorLink";
import { FilterSection, FilterLink } from "@/app/products/FilterSection";
import MobileFilterDrawer from "@/app/products/MobileFilterDrawer";
import ActiveFilters from "@/app/products/ActiveFilters";
import SortDropdown from "@/app/products/SortDropdown";
import Link from "next/link";
import type { FilterOptions } from "@/types";

export const revalidate = 60;

interface SearchParams {
  category_id?: string;
  brand_id?: string;
  color_id?: string;
  size_id?: string;
  gender_id?: string;
  season_id?: string;
  search?: string;
  sort?: string;
  page?: string;
  price_min?: string;
  price_max?: string;
}

export default async function ProductsPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>;
}) {
  const headersList = await headers();
  const tenantSlug = headersList.get("x-tenant-slug") || "default";
  const cookieHeader = headersList.get("cookie") ?? "";
  const t = getTranslations(getLocaleFromCookie(cookieHeader));
  const params = await searchParams;

  const filterParams: Record<string, string> = {};
  for (const [k, v] of Object.entries(params)) {
    if (v) filterParams[k] = v;
  }

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

  const products = productsRes.data ?? [];
  const filters = filtersRes.filters ?? {};
  const meta = productsRes.meta ?? {
    current_page: 1,
    last_page: 1,
    per_page: 24,
    total: 0,
  };
  const currency = (configRes?.website as any)?.currency ?? "EGP";
  const templateId = (configRes?.website as any)?.template_id ?? "default";
  const template = getTemplate(templateId);

  const buildUrl = (overrides: Record<string, string | undefined>) => {
    const next = { ...filterParams, ...overrides };
    const qs = new URLSearchParams(
      Object.fromEntries(
        Object.entries(next).filter(([, v]) => v != null),
      ) as Record<string, string>,
    ).toString();
    return `/products${qs ? "?" + qs : ""}`;
  };

  const activeFilterCount = Object.keys(filterParams).filter(
    (k) => !["page", "sort"].includes(k),
  ).length;

  const productGridClass =
    template.productGrid === "grid-3"
      ? "grid gap-5 lg:gap-6 grid-cols-2 sm:grid-cols-3"
      : template.productGrid === "grid-2"
        ? "grid gap-5 lg:gap-6 grid-cols-2"
        : "grid gap-5 lg:gap-6 grid-cols-2 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4";

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 lg:py-10">
        {/* Page Header */}
        <div className="mb-6 lg:mb-8">
          <nav className="breadcrumb mb-3">
            <Link href="/">{t.common.home}</Link>
            <span className="breadcrumb-separator">
              <svg
                className="w-3 h-3"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={2}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M9 5l7 7-7 7"
                />
              </svg>
            </span>
            <span className="text-gray-900 font-medium">
              {t.filters.products}
            </span>
          </nav>
          <h1 className="section-heading">
            {params.search
              ? `${t.search.resultsCount.replace("{{count}}", String(meta.total))}`
              : t.nav.products}
          </h1>
          {params.search && (
            <p className="section-subheading">
              {t.search.for} "{params.search}"
            </p>
          )}
        </div>

        {/* Active Filter Chips */}
        <ActiveFilters
          filterParams={filterParams}
          filters={filters}
          t={t}
        />

        <div className="flex flex-col lg:flex-row gap-6 lg:gap-8">
        {/* ── Sidebar Filters (Desktop) ── */}
        <aside className="hidden lg:block w-72 flex-shrink-0">
          <div className="bg-gray-50/80 rounded-2xl border border-gray-200 p-6 sticky top-24 shadow-sm">
            <div className="flex items-center justify-between mb-5">
              <h2 className="text-sm font-bold text-gray-900 uppercase tracking-wider">
                {t.filters.title}
              </h2>
              {activeFilterCount > 0 && (
                <Link
                  href="/products"
                  className="text-xs font-semibold px-2.5 py-1.5 rounded-lg bg-white border border-gray-200 text-gray-600 hover:bg-gray-100 hover:text-gray-900 transition-colors"
                >
                  {t.filters.clearAll}
                </Link>
              )}
            </div>

            {/* Search */}
            <form method="get" action="/products" className="mb-5">
              {Object.entries(filterParams)
                .filter(([k]) => k !== "search")
                .map(([k, v]) => (
                  <input key={k} type="hidden" name={k} value={v} />
                ))}
              <div className="relative">
                <input
                  type="text"
                  name="search"
                  defaultValue={params.search}
                  placeholder={t.filters.searchPlaceholder}
                  className="w-full border-2 border-gray-200 rounded-xl pl-10 pr-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary bg-white transition-all placeholder:text-gray-400"
                />
                <svg
                  className="absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  strokeWidth={2}
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M21 21l-4.35-4.35M17 11A6 6 0 115 11a6 6 0 0112 0z"
                  />
                </svg>
              </div>
            </form>

            {/* Categories */}
            {filters.categories && filters.categories.length > 0 && (
              <FilterSection title={t.filters.category}>
                {filters.categories.map((c) => (
                  <FilterLink
                    key={c.id}
                    href={buildUrl({
                      category_id: String(c.id),
                      page: undefined,
                    })}
                    active={params.category_id === String(c.id)}
                    label={c.name}
                  />
                ))}
              </FilterSection>
            )}

            {/* Sizes */}
            {filters.sizes && filters.sizes.length > 0 && (
              <FilterSection title={t.filters.size}>
                <div className="flex flex-wrap gap-2">
                  {filters.sizes.map((s) => {
                    const isActive = params.size_id === String(s.id);
                    return (
                      <Link
                        key={s.id}
                        href={buildUrl({
                          size_id: String(s.id),
                          page: undefined,
                        })}
                        className={`inline-flex items-center justify-center min-w-[2.5rem] px-3.5 py-2.5 rounded-lg text-sm font-semibold border-2 transition-all ${
                          isActive
                            ? "text-white border-transparent shadow-sm"
                            : "text-gray-700 bg-gray-50 border-transparent hover:bg-gray-100 hover:border-gray-200"
                        }`}
                        style={
                          isActive
                            ? { backgroundColor: "var(--color-primary)" }
                            : undefined
                        }
                      >
                        {s.name}
                      </Link>
                    );
                  })}
                </div>
              </FilterSection>
            )}

            {/* Colors */}
            {filters.colors && filters.colors.length > 0 && (
              <FilterSection title={t.filters.color}>
                <div className="flex flex-wrap gap-2">
                  {filters.colors.map((c) => (
                    <FilterColorLink
                      key={c.id}
                      href={buildUrl({
                        color_id: String(c.id),
                        page: undefined,
                      })}
                      active={params.color_id === String(c.id)}
                      color={c}
                    />
                  ))}
                </div>
              </FilterSection>
            )}

            {/* Price Range */}
            {filters.price_range &&
              filters.price_range.min < filters.price_range.max && (
                <FilterSection title={t.filters.price}>
                  <PriceRangeSlider
                    min={Math.floor(filters.price_range.min)}
                    max={Math.ceil(filters.price_range.max)}
                    currency={currency}
                    labelMin={t.filters.priceMin}
                    labelMax={t.filters.priceMax}
                  />
                </FilterSection>
              )}

            {/* Brands */}
            {filters.brands && filters.brands.length > 0 && (
              <FilterSection title={t.filters.brand}>
                {filters.brands.map((b) => (
                  <FilterLink
                    key={b.id}
                    href={buildUrl({ brand_id: String(b.id), page: undefined })}
                    active={params.brand_id === String(b.id)}
                    label={b.name}
                  />
                ))}
              </FilterSection>
            )}
          </div>
        </aside>

        {/* ── Product Grid ── */}
        <div className="flex-1 min-w-0">
          {/* Toolbar row: product count and sort side by side (Amazon-style) */}
          <div className="bg-white rounded-2xl border border-gray-200 p-4 mb-6 flex flex-wrap items-center justify-between gap-4 shadow-sm">
            <div className="flex items-center gap-3 min-w-0">
              <MobileFilterDrawer
                filters={filters}
                currentParams={filterParams}
                currency={currency}
                t={t}
              />
              <p className="text-sm text-gray-600 truncate">
                {meta.total > 0 ? (
                  <>
                    <span className="font-semibold text-gray-900">
                      {meta.total}
                    </span>{" "}
                    {t.filters.products}
                  </>
                ) : (
                  t.filters.noProducts
                )}
              </p>
            </div>
            <div className="flex items-center gap-2 flex-shrink-0">
              <label className="text-sm font-medium text-gray-600 whitespace-nowrap">
                {t.filters.sort}:
              </label>
              <SortDropdown
                currentSort={params.sort}
                t={t}
              />
            </div>
          </div>

          {products.length === 0 ? (
            <div className="text-center py-20 lg:py-32 bg-white rounded-xl border border-gray-200">
              <div className="w-20 h-20 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-6">
                <svg
                  className="w-10 h-10 text-gray-400"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  strokeWidth={1.5}
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M21 21l-4.35-4.35M17 11A6 6 0 115 11a6 6 0 0112 0z"
                  />
                </svg>
              </div>
              <h3 className="text-lg font-bold text-gray-900 mb-2">
                {t.filters.noMatchFilters}
              </h3>
              <p className="text-sm text-gray-500 mb-8 max-w-md mx-auto">
                {t.filters.tryAdjusting}
              </p>
              <Link
                href="/products"
                className="btn-refined btn-refined-primary inline-flex"
              >
                {t.filters.clearFilters}
              </Link>
            </div>
          ) : (
            <div className={productGridClass}>
              {products.map((p) => (
                <ProductCard
                  key={p.id}
                  product={p}
                  currency={currency}
                  template={template}
                />
              ))}
            </div>
          )}

          {/* Pagination */}
          {meta.last_page > 1 && (
            <div className="flex items-center justify-center gap-2 mt-10 lg:mt-12">
              {meta.current_page > 1 && (
                <Link
                  href={buildUrl({ page: String(meta.current_page - 1) })}
                  className="w-10 h-10 flex items-center justify-center rounded-lg 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>
              )}
              <div className="flex items-center gap-1.5">
                {Array.from({ length: Math.min(meta.last_page, 7) }, (_, i) => {
                  const page = i + 1;
                  const isCurrent = page === meta.current_page;
                  const linkStyle = isCurrent
                    ? { backgroundColor: "var(--color-primary)" }
                    : undefined;
                  return (
                    <Link
                      key={page}
                      href={buildUrl({ page: String(page) })}
                      className={`w-10 h-10 flex items-center justify-center rounded-lg text-sm font-semibold transition-all ${
                        isCurrent
                          ? "text-white shadow-sm"
                          : "border border-gray-200 text-gray-600 hover:bg-gray-50 hover:border-gray-300"
                      }`}
                      style={linkStyle}
                    >
                      {page}
                    </Link>
                  );
                })}
                {meta.last_page > 7 && (
                  <span className="w-10 h-10 flex items-center justify-center text-sm text-gray-400">
                    …
                  </span>
                )}
              </div>
              {meta.current_page < meta.last_page && (
                <Link
                  href={buildUrl({ page: String(meta.current_page + 1) })}
                  className="w-10 h-10 flex items-center justify-center rounded-lg 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>
      </div>
    </div>
    </div>
  );
}
