import Link from "next/link";
import { notFound } from "next/navigation";
import { SlidersHorizontal, X } from "lucide-react";
import { isLocale, type Locale } from "@/lib/i18n/config";
import { getDictionary } from "@/lib/i18n";
import { categoryTitle, getCategories, getProducts } from "@/lib/catalog";
import { parseCatalogSearch } from "@/lib/search-params";
import { buildMetadata } from "@/lib/seo";
import { centsToInput } from "@/lib/money";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ProductCard } from "@/components/store/product-card";
import { Pagination } from "@/components/store/pagination";
import { ShopSort } from "@/components/store/shop-sort";

export async function generateMetadata({ params }: { params: Promise<{ locale: string }> }) {
  const { locale: raw } = await params;
  if (!isLocale(raw)) return {};
  const locale = raw as Locale;
  const dict = getDictionary(locale);
  return buildMetadata({
    locale,
    title: dict.meta.shopTitle,
    description: dict.meta.shopDescription,
    path: "/shop",
  });
}

export default async function ShopPage({
  params,
  searchParams,
}: {
  params: Promise<{ locale: string }>;
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const { locale: raw } = await params;
  if (!isLocale(raw)) notFound();
  const locale = raw as Locale;
  const dict = getDictionary(locale);
  const query = parseCatalogSearch(await searchParams);

  const [categories, results] = await Promise.all([getCategories(), getProducts(query)]);
  const activeCategory = categories.find((category) => category.slug === query.category);
  const title = activeCategory ? categoryTitle(activeCategory, locale) : dict.shop.title;
  const description = activeCategory
    ? categories.find((category) => category.id === activeCategory.id)?.translations.find((t) => t.locale === locale)?.description ??
      dict.shop.description
    : dict.shop.description;

  const hasFilters =
    Boolean(query.q || query.category || query.featured) ||
    query.min !== undefined ||
    query.max !== undefined ||
    query.inStock;

  const keepParams: Record<string, string | undefined> = {
    q: query.q || undefined,
    category: query.category || undefined,
    min: query.min ? centsToInput(query.min) : undefined,
    max: query.max ? centsToInput(query.max) : undefined,
    inStock: query.inStock ? "1" : undefined,
    featured: query.featured ? "1" : undefined,
    sort: query.sort,
  };

  const Filters = ({ idPrefix }: { idPrefix: string }) => (
    <form action={`/${locale}/shop`} method="get" className="space-y-7">
      <input type="hidden" name="sort" value={query.sort} />
      <div>
        <label htmlFor={`${idPrefix}-q`} className="field-label">
          {dict.common.search}
        </label>
        <div className="relative">
          <Input
            id={`${idPrefix}-q`}
            name="q"
            defaultValue={query.q}
            placeholder={dict.shop.searchPlaceholder}
            className="h-11 bg-transparent pr-9 text-xs"
          />
        </div>
      </div>

      <fieldset>
        <legend className="field-label">{dict.shop.category}</legend>
        <div className="space-y-2.5">
          <label className="flex cursor-pointer items-center gap-2.5 text-[14px] text-charcoal/65">
            <input
              type="radio"
              name="category"
              value=""
              defaultChecked={!query.category}
              className="h-3 w-3 accent-[#24221D]"
            />
            {dict.shop.allCategories}
          </label>
          {categories.map((category) => (
            <label
              key={`${idPrefix}-${category.id}`}
              className="flex cursor-pointer items-center justify-between gap-2 text-[14px] text-charcoal/65"
            >
              <span className="flex items-center gap-2.5">
                <input
                  type="radio"
                  name="category"
                  value={category.slug}
                  defaultChecked={query.category === category.slug}
                  className="h-3 w-3 accent-[#24221D]"
                />
                {categoryTitle(category, locale)}
              </span>
              <span className="text-[12px] text-charcoal/30">{category._count.products}</span>
            </label>
          ))}
        </div>
      </fieldset>

      <div>
        <p className="field-label">{dict.shop.price}</p>
        <div className="flex items-center gap-2">
          <Input
            name="min"
            type="number"
            min={0}
            inputMode="numeric"
            defaultValue={query.min ? centsToInput(query.min) : ""}
            placeholder={dict.shop.minPrice}
            aria-label={dict.shop.minPrice}
            className="h-10 bg-transparent text-xs"
          />
          <span className="text-charcoal/30">—</span>
          <Input
            name="max"
            type="number"
            min={0}
            inputMode="numeric"
            defaultValue={query.max ? centsToInput(query.max) : ""}
            placeholder={dict.shop.maxPrice}
            aria-label={dict.shop.maxPrice}
            className="h-10 bg-transparent text-xs"
          />
        </div>
      </div>

      <fieldset className="space-y-3">
        <legend className="field-label">{dict.shop.availability}</legend>
        <label className="flex cursor-pointer items-center gap-2.5 text-[14px] text-charcoal/65">
          <input
            type="checkbox"
            name="inStock"
            value="1"
            defaultChecked={query.inStock}
            className="h-3.5 w-3.5 accent-[#24221D]"
          />
          {dict.shop.inStockOnly}
        </label>
        <label className="flex cursor-pointer items-center gap-2.5 text-[14px] text-charcoal/65">
          <input
            type="checkbox"
            name="featured"
            value="1"
            defaultChecked={query.featured}
            className="h-3.5 w-3.5 accent-[#24221D]"
          />
          {dict.shop.featuredOnly}
        </label>
      </fieldset>

      <div className="space-y-3 border-t border-border pt-6">
        <Button type="submit" className="w-full">
          {dict.shop.apply}
        </Button>
        {hasFilters && (
          <Link
            href={`/${locale}/shop`}
            className="block text-center text-[12px] uppercase tracking-[0.14em] text-charcoal/45 underline-offset-4 hover:text-charcoal hover:underline"
          >
            {dict.shop.clear}
          </Link>
        )}
      </div>
    </form>
  );

  return (
    <>
      <section className="border-b border-border bg-cream/40">
        <div className="shell py-12 md:py-16">
          <nav className="flex items-center gap-2 text-[12px] uppercase tracking-[0.16em] text-charcoal/40">
            <Link href={`/${locale}`} className="hover:text-charcoal">
              {dict.nav.home}
            </Link>
            <span>/</span>
            <span className="text-charcoal/70">{dict.nav.shop}</span>
            {activeCategory && (
              <>
                <span>/</span>
                <span className="text-charcoal/70">{title}</span>
              </>
            )}
          </nav>
          <div className="mt-5 flex flex-col justify-between gap-5 md:flex-row md:items-end">
            <div>
              <h1 className="font-serif text-4xl font-light tracking-tight md:text-5xl">{title}</h1>
              <p className="mt-3 max-w-xl text-[14px] leading-relaxed text-charcoal/55 md:text-[15px]">
                {description}
              </p>
            </div>
            <p className="text-[12px] uppercase tracking-[0.14em] text-charcoal/40">
              {results.total} {dict.shop.productsCount}
            </p>
          </div>
        </div>
      </section>

      <div className="shell py-10 md:py-14">
        <div className="flex items-center justify-between gap-4 border-b border-border pb-5">
          <details className="group lg:hidden">
            <summary className="flex cursor-pointer list-none items-center gap-2 text-[12px] uppercase tracking-[0.14em] text-charcoal">
              <SlidersHorizontal className="h-3.5 w-3.5" />
              {dict.shop.filters}
            </summary>
            <div className="absolute left-0 right-0 z-30 mt-4 border border-border bg-ivory p-5 shadow-luxe">
              <Filters idPrefix="mobile" />
            </div>
          </details>

          <p className="hidden text-[12px] uppercase tracking-[0.14em] text-charcoal/40 lg:block">
            {results.total === 0
              ? dict.shop.noResults
              : `${dict.shop.showing} ${(results.page - 1) * results.pageSize + 1}–${Math.min(results.page * results.pageSize, results.total)} ${dict.shop.of} ${results.total}`}
          </p>

          <div className="flex items-center gap-4">
            {hasFilters && (
              <Link
                href={`/${locale}/shop`}
                className="hidden items-center gap-1.5 text-[12px] uppercase tracking-[0.12em] text-charcoal/40 hover:text-charcoal sm:flex"
              >
                <X className="h-3 w-3" />
                {dict.shop.clear}
              </Link>
            )}
            <ShopSort locale={locale} value={query.sort} labels={{ ...dict.sort, label: dict.shop.sort }} />
          </div>
        </div>

        <div className="mt-8 grid gap-10 lg:grid-cols-[240px_1fr] lg:gap-12">
          <aside className="hidden lg:block">
            <div className="sticky top-32">
              <Filters idPrefix="desktop" />
            </div>
          </aside>

          <div>
            {results.items.length === 0 ? (
              <div className="flex min-h-[380px] flex-col items-center justify-center border border-dashed border-border px-6 text-center">
                <p className="font-serif text-2xl text-charcoal">{dict.shop.noResults}</p>
                <p className="mt-2 max-w-sm text-[14px] leading-relaxed text-charcoal/50">
                  {dict.shop.noResultsDesc}
                </p>
                <Button asChild variant="outline" className="mt-6">
                  <Link href={`/${locale}/shop`}>{dict.shop.clear}</Link>
                </Button>
              </div>
            ) : (
              <div className="grid grid-cols-2 gap-x-4 gap-y-10 md:grid-cols-3 md:gap-x-5">
                {results.items.map((product, index) => (
                  <ProductCard
                    key={product.id}
                    product={product}
                    locale={locale}
                    dict={dict}
                    priority={index < 3}
                    titleClassName="text-[20px] md:text-2xl"
                  />
                ))}
              </div>
            )}

            <Pagination
              page={results.page}
              totalPages={results.totalPages}
              basePath={`/${locale}/shop`}
              params={keepParams}
              labels={{ previous: dict.shop.previous, next: dict.shop.next }}
            />
          </div>
        </div>
      </div>
    </>
  );
}
