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 Link from "next/link";

export const revalidate = 0;

interface SearchPageProps {
  searchParams: Promise<{ q?: string; page?: string }>;
}

export default async function SearchPage({ searchParams }: SearchPageProps) {
  const headersList = await headers();
  const tenantSlug = headersList.get("x-tenant-slug") || "default";
  const cookieHeader = headersList.get("cookie") ?? "";
  const locale = getLocaleFromCookie(cookieHeader);
  const t = getTranslations(locale);
  const { q = "", page = "1" } = await searchParams;

  const configRes = await storefrontApi.getConfig(tenantSlug).catch(() => null);
  const currency = (configRes?.website as any)?.currency ?? "EGP";
  const templateId = (configRes?.website as any)?.template_id ?? "default";
  const template = getTemplate(templateId);

  const productsRes = q.trim()
    ? await storefrontApi
        .getProducts(tenantSlug, { search: q.trim(), page, per_page: "24" })
        .catch(() => ({
          data: [],
          meta: { current_page: 1, last_page: 1, per_page: 24, total: 0 },
          links: {},
        }))
    : {
        data: [],
        meta: { current_page: 1, last_page: 1, per_page: 24, total: 0 },
        links: {},
      };

  const products = productsRes.data ?? [];
  const meta = productsRes.meta ?? {
    current_page: 1,
    last_page: 1,
    per_page: 24,
    total: 0,
  };

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      {/* Header */}
      <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">{t.search.title}</span>
        </nav>

        {q ? (
          <>
            <h1 className="text-2xl font-bold text-gray-900">
              {t.search.for}{" "}
              <span className="italic text-gray-600">&ldquo;{q}&rdquo;</span>
            </h1>
            <p className="text-sm text-gray-400 mt-1">
              {t.search.resultsCount.replace(
                /\{\{\s*count\s*\}\}/g,
                String(meta.total),
              )}
            </p>
          </>
        ) : (
          <>
            <h1 className="text-2xl font-bold text-gray-900">
              {t.search.title}
            </h1>
            <p className="text-sm text-gray-400 mt-1">{t.search.enterTerm}</p>
          </>
        )}
      </div>

      {/* Search form */}
      <form method="GET" action="/search" className="mb-10">
        <div className="relative max-w-xl">
          <input
            type="search"
            name="q"
            defaultValue={q}
            placeholder={t.nav.search}
            autoFocus={!q}
            className="w-full pl-11 pr-28 py-3.5 rounded-2xl text-sm border border-gray-200 bg-white shadow-sm focus:outline-none focus:border-gray-300 transition-all"
          />
          <svg
            className="absolute left-4 top-1/2 -translate-y-1/2 h-4.5 w-4.5 text-gray-400"
            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>
          <button
            type="submit"
            className="absolute right-2 top-1/2 -translate-y-1/2 px-5 py-2 rounded-xl text-sm font-semibold text-white transition-opacity hover:opacity-90"
            style={{ backgroundColor: "var(--color-primary)" }}
          >
            {t.search.search}
          </button>
        </div>
      </form>

      {/* No results */}
      {q && products.length === 0 && (
        <div className="text-center py-20">
          <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="M21 21l-4.35-4.35M17 11A6 6 0 115 11a6 6 0 0112 0z"
              />
            </svg>
          </div>
          <p className="text-lg font-semibold text-gray-700 mb-2">
            {t.search.noResults}
          </p>
          <p className="text-sm text-gray-400 mb-6">{t.search.tryDifferent}</p>
          <Link
            href="/products"
            className="text-sm font-semibold hover:underline"
            style={{ color: "var(--color-primary)" }}
          >
            {t.search.browseAll}
          </Link>
        </div>
      )}

      {products.length > 0 && (
        <>
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 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={`/search?q=${encodeURIComponent(q)}&page=${
                    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.search.pageOf
                  .replace(/\{\{\s*current\s*\}\}/g, String(meta.current_page))
                  .replace(/\{\{\s*total\s*\}\}/g, String(meta.last_page))}
              </span>
              {meta.current_page < meta.last_page && (
                <Link
                  href={`/search?q=${encodeURIComponent(q)}&page=${
                    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>
  );
}
