"use client";

import React, { useState, useMemo } from "react";
import IntentLink from "@/components/IntentLink";
import Image from "next/image";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { ArrowRight, ImageIcon, RotateCcw, Search, SlidersHorizontal, X } from "lucide-react";
import { useTranslations } from "next-intl";
import { motion, AnimatePresence, useReducedMotion } from "framer-motion";
import {
  getProductCatalogFacets,
  getProductFormatLabels,
  localizeProductDescription,
  localizeProductName,
  localizeSeriesName,
  localizeSurface,
} from "@/lib/product-i18n";
import SeriesCatalogBanner from "@/components/SeriesCatalogBanner";
import type { NordenCollection } from "@/lib/collections";

interface ProductImage {
  id: string;
  url: string;
  alt: string | null;
  order: number;
}

interface ProductSeries {
  id: string;
  name: string;
  slug: string | null;
}

interface ProductCategory {
  id: string;
  name: string;
  slug: string;
}

interface UnifiedProduct {
  id: string;
  name: string;
  nameTr: string | null;
  nameEn: string | null;
  nameRu: string | null;
  slug: string;
  sku: string | null;
  widthCm: number | null;
  surface: string | null;
  burnerCount: number | null;
  description: string | null;
  descriptionTr: string | null;
  descriptionEn: string | null;
  descriptionRu: string | null;
  images: ProductImage[];
  series: ProductSeries | null;
  category: ProductCategory;
}

interface ProductsPageClientProps {
  products: UnifiedProduct[];
  categories: ProductCategory[];
  locale: string;
  collections: NordenCollection[];
}

export default function ProductsPageClient({ products, categories, locale, collections }: ProductsPageClientProps) {
  const t = useTranslations();
  const searchParams = useSearchParams();
  const pathname = usePathname();
  const router = useRouter();
  const reduceMotion = useReducedMotion();
  const urlCategory = searchParams.get("category");
  const urlSeries = searchParams.get("series");
  const urlSurface = searchParams.get("surface");
  const urlWidth = searchParams.get("width");
  const searchQuery = searchParams.get("q") ?? "";
  const [mobileFiltersOpen, setMobileFiltersOpen] = useState(false);
  const availableCatalogFacets = useMemo(
    () => Array.from(new Set(products.flatMap((product) => getProductCatalogFacets(product)))),
    [products],
  );

  const selectedCategory = categories.find((category) => category.slug === urlCategory)?.id ?? "all";
  const normalizedUrlSeries = urlSeries?.toLocaleLowerCase("en-US");
  const selectedSeriesRecord = products.find((product) => {
    const series = product.series;
    if (!series || !normalizedUrlSeries) return false;
    return [series.slug, series.name].some((value) => value?.toLocaleLowerCase("en-US") === normalizedUrlSeries);
  })?.series;
  const selectedSeries = selectedSeriesRecord?.name ?? "all";
  const selectedWidth = products.some((product) => product.widthCm?.toString() === urlWidth) ? urlWidth ?? "all" : "all";
  const selectedSurface = availableCatalogFacets.find(
    (facet) => facet.toLocaleLowerCase("tr") === urlSurface?.toLocaleLowerCase("tr"),
  ) ?? "all";
  const widthUnit = locale === "ru" ? "см" : "cm";

  const updateParams = (updates: Record<string, string | null>, replace = false) => {
    const params = new URLSearchParams(searchParams.toString());
    Object.entries(updates).forEach(([key, value]) => {
      if (!value || value === "all") params.delete(key);
      else params.set(key, value);
    });
    const href = params.size ? `${pathname}?${params.toString()}` : pathname;
    if (replace) router.replace(href, { scroll: false });
    else router.push(href, { scroll: false });
  };

  // Compute dynamic filter options
  const filterOptions = useMemo(() => {
    const seriesSet = new Set<string>();
    const widthsSet = new Set<number>();
    const surfacesSet = new Set<string>();

    products.forEach((p) => {
      const matchCat = selectedCategory === "all" || p.category.id === selectedCategory;
      if (!matchCat) return;
      if (p.series?.name) seriesSet.add(p.series.name);
      if (p.widthCm) widthsSet.add(p.widthCm);
      getProductCatalogFacets(p).forEach((facet) => surfacesSet.add(facet));
    });

    return {
      series: Array.from(seriesSet).sort(),
      widths: Array.from(widthsSet).sort((a, b) => a - b),
      surfaces: Array.from(surfacesSet).sort(
        (a, b) => ["Inox", "Siyah Cam", "Ceran"].indexOf(a) - ["Inox", "Siyah Cam", "Ceran"].indexOf(b),
      ),
    };
  }, [products, selectedCategory]);

  const handleCategorySelect = (id: string) => {
    const category = categories.find((item) => item.id === id);
    updateParams({ category: category?.slug ?? null, series: null });
  };

  const handleResetFilters = () => {
    router.push(pathname, { scroll: false });
  };

  const filteredProducts = useMemo(() => {
    const normalizedQuery = searchQuery.trim().toLocaleLowerCase(locale);
    return products.filter((product) => {
      const searchValues = [
        localizeProductName(product, locale),
        localizeProductDescription(product, locale),
        localizeSeriesName(product.series?.name),
        ...getProductFormatLabels(product, locale),
        product.sku,
        product.widthCm?.toString(),
        product.burnerCount?.toString(),
      ];
      const matchesSearch = !normalizedQuery || searchValues.some((value) => value?.toLocaleLowerCase(locale).includes(normalizedQuery));

      const matchesCategory = selectedCategory === "all" || product.category.id === selectedCategory;
      const matchesSeries = selectedSeries === "all" || product.series?.name === selectedSeries;
      const matchesWidth = selectedWidth === "all" || product.widthCm?.toString() === selectedWidth;
      const matchesSurface = selectedSurface === "all" || getProductCatalogFacets(product).includes(selectedSurface);

      return matchesSearch && matchesCategory && matchesSeries && matchesWidth && matchesSurface;
    });
  }, [products, searchQuery, selectedCategory, selectedSeries, selectedWidth, selectedSurface, locale]);

  const hasActiveFilters =
    selectedCategory !== "all" ||
    selectedSeries !== "all" ||
    selectedWidth !== "all" ||
    selectedSurface !== "all" ||
    searchQuery !== "";

  const activeFilters = [
    selectedCategory !== "all" ? { key: "category", label: categories.find((item) => item.id === selectedCategory)?.slug === "hobs" ? t("nav.hobs") : categories.find((item) => item.id === selectedCategory)?.name ?? "", clear: () => updateParams({ category: null, series: null }) } : null,
    selectedSeries !== "all" ? { key: "series", label: localizeSeriesName(selectedSeries), clear: () => updateParams({ series: null }) } : null,
    selectedWidth !== "all" ? { key: "width", label: `${selectedWidth} ${widthUnit}`, clear: () => updateParams({ width: null }) } : null,
    selectedSurface !== "all" ? { key: "surface", label: localizeSurface(selectedSurface, locale) ?? selectedSurface, clear: () => updateParams({ surface: null }) } : null,
    searchQuery ? { key: "q", label: `“${searchQuery}”`, clear: () => updateParams({ q: null }, true) } : null,
  ].filter((item): item is { key: string; label: string; clear: () => void } => Boolean(item));

  return (
    <div className="w-full max-w-7xl mx-auto px-6 md:px-12 pt-32 pb-24 flex flex-col gap-12">
      {/* Title Header */}
      <motion.div
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.8 }}
        className="flex flex-col gap-4 text-center md:text-left"
      >
        <span className="eyebrow">{t("featured.eyebrow")}</span>
        <h1 className="section-title">{t("categories.title")}</h1>
        <p className="text-sm max-w-xl" style={{ color: "var(--fg-secondary)", lineHeight: "var(--leading-normal)" }}>
          {t("categories.hobs_desc")}
        </p>
      </motion.div>

      <button type="button" onClick={() => setMobileFiltersOpen((open) => !open)} className="flex min-h-11 items-center justify-between rounded-2xl border border-border bg-surface-1 px-5 text-xs font-semibold uppercase tracking-[0.15em] text-fg-primary lg:hidden" aria-expanded={mobileFiltersOpen} aria-controls="catalog-filters">
        <span className="flex items-center gap-2"><SlidersHorizontal size={15} className="text-ember" />{t("catalog.filters")}</span>
        <span className="rounded-full bg-ember/10 px-2.5 py-1 text-ember">{activeFilters.length}</span>
      </button>

      {/* Main Layout Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-10 items-start">
        {/* Filters Sidebar */}
        <aside id="catalog-filters" className={`${mobileFiltersOpen ? "flex" : "hidden"} max-h-[70svh] flex-col gap-8 overflow-y-auto overscroll-contain rounded-3xl p-6 liquid-glass [scrollbar-width:none] [&::-webkit-scrollbar]:hidden lg:sticky lg:top-28 lg:col-span-3 lg:flex lg:max-h-[calc(100svh-8rem)]`} style={{ border: "1px solid var(--border)" }}>
          <div className="flex items-center justify-between pb-4 border-b" style={{ borderColor: "var(--border)" }}>
            <span className="text-xs font-mono uppercase tracking-widest font-semibold flex items-center gap-2" style={{ color: "var(--fg-primary)" }}>
              <SlidersHorizontal size={14} style={{ color: "var(--ember)" }} />
              {t("catalog.filters")}
            </span>
            {hasActiveFilters && (
              <button
                type="button"
                onClick={handleResetFilters}
                className="flex min-h-11 items-center gap-1.5 px-2 text-[11px] font-mono uppercase tracking-wider transition-colors"
                style={{ color: "var(--ember)" }}
              >
                <RotateCcw size={12} /> {t("catalog.reset")}
              </button>
            )}
          </div>

          {/* Category Filter */}
          <div className="flex flex-col gap-3">
            <h3 className="text-xs font-mono uppercase tracking-widest" style={{ color: "var(--fg-muted)" }}>
              {t("catalog.category")}
            </h3>
            <div className="flex flex-col gap-1.5">
              <button
                onClick={() => handleCategorySelect("all")}
                className="min-h-11 w-full text-left px-4 py-2.5 rounded-xl text-xs transition-all flex items-center justify-between"
                style={{
                  background: selectedCategory === "all" ? "rgba(196,147,90,0.1)" : "transparent",
                  color: selectedCategory === "all" ? "var(--ember-bright)" : "var(--fg-secondary)",
                  border: selectedCategory === "all" ? "1px solid var(--ember-muted)" : "1px solid transparent",
                }}
              >
                <span>{t("catalog.all_products")}</span>
              </button>
              {categories.map((cat) => (
                <button
                  key={cat.id}
                  onClick={() => handleCategorySelect(cat.id)}
                  className="min-h-11 w-full text-left px-4 py-2.5 rounded-xl text-xs transition-all flex items-center justify-between"
                  style={{
                    background: selectedCategory === cat.id ? "rgba(196,147,90,0.1)" : "transparent",
                    color: selectedCategory === cat.id ? "var(--ember-bright)" : "var(--fg-secondary)",
                    border: selectedCategory === cat.id ? "1px solid var(--ember-muted)" : "1px solid transparent",
                  }}
                >
                  <span>{cat.slug === "hobs" ? t("nav.hobs") : cat.name}</span>
                </button>
              ))}
            </div>
          </div>

          {/* Series Filter */}
          {filterOptions.series.length > 0 && (
            <div className="flex flex-col gap-3">
              <h3 className="text-xs font-mono uppercase tracking-widest" style={{ color: "var(--fg-muted)" }}>
                {t("catalog.series")}
              </h3>
              <div className="flex flex-col gap-1.5">
                <button
                  onClick={() => updateParams({ series: null })}
                  className="min-h-11 w-full text-left px-4 py-2 rounded-xl text-xs transition-all"
                  style={{
                    color: selectedSeries === "all" ? "var(--ember-bright)" : "var(--fg-secondary)",
                    background: selectedSeries === "all" ? "rgba(196,147,90,0.08)" : "transparent",
                  }}
                >
                  {t("catalog.all_series")}
                </button>
                {filterOptions.series.map((name) => (
                  <button
                    key={name}
                    onClick={() => updateParams({ series: products.find((product) => product.series?.name === name)?.series?.slug ?? name })}
                    className="min-h-11 w-full text-left px-4 py-2 rounded-xl text-xs transition-all"
                    style={{
                      color: selectedSeries === name ? "var(--ember-bright)" : "var(--fg-secondary)",
                      background: selectedSeries === name ? "rgba(196,147,90,0.08)" : "transparent",
                    }}
                  >
                    {localizeSeriesName(name)}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Width Filter */}
          {filterOptions.widths.length > 0 && (
            <div className="flex flex-col gap-3">
              <h3 className="text-xs font-mono uppercase tracking-widest" style={{ color: "var(--fg-muted)" }}>
                {t("catalog.width")}
              </h3>
              <div className="flex flex-wrap gap-2">
                <button
                  onClick={() => updateParams({ width: null })}
                  className="min-h-11 px-3 py-1.5 rounded-full text-xs font-mono transition-all"
                  style={{
                    background: selectedWidth === "all" ? "rgba(196,147,90,0.12)" : "rgba(128,128,160,0.06)",
                    color: selectedWidth === "all" ? "var(--ember-bright)" : "var(--fg-secondary)",
                    border: `1px solid ${selectedWidth === "all" ? "var(--ember)" : "var(--border)"}`,
                  }}
                >
                  {t("catalog.all")}
                </button>
                {filterOptions.widths.map((w) => (
                  <button
                    key={w}
                    onClick={() => updateParams({ width: w.toString() })}
                    className="min-h-11 px-3 py-1.5 rounded-full text-xs font-mono transition-all"
                    style={{
                      background: selectedWidth === w.toString() ? "rgba(196,147,90,0.12)" : "rgba(128,128,160,0.06)",
                      color: selectedWidth === w.toString() ? "var(--ember-bright)" : "var(--fg-secondary)",
                      border: `1px solid ${selectedWidth === w.toString() ? "var(--ember)" : "var(--border)"}`,
                    }}
                  >
                    {w} {widthUnit}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Surface Filter */}
          {filterOptions.surfaces.length > 0 && (
            <div className="flex flex-col gap-3">
              <h3 className="text-xs font-mono uppercase tracking-widest" style={{ color: "var(--fg-muted)" }}>
                {t("catalog.surface")}
              </h3>
              <div className="flex flex-wrap gap-2">
                <button
                  onClick={() => updateParams({ surface: null })}
                  className="min-h-11 px-3 py-1.5 rounded-full text-xs transition-all"
                  style={{
                    background: selectedSurface === "all" ? "rgba(196,147,90,0.12)" : "rgba(128,128,160,0.06)",
                    color: selectedSurface === "all" ? "var(--ember-bright)" : "var(--fg-secondary)",
                    border: `1px solid ${selectedSurface === "all" ? "var(--ember)" : "var(--border)"}`,
                  }}
                >
                  {t("catalog.all")}
                </button>
                {filterOptions.surfaces.map((s) => (
                  <button
                    key={s}
                    onClick={() => updateParams({ surface: s })}
                    className="min-h-11 px-3 py-1.5 rounded-full text-xs transition-all"
                    style={{
                      background: selectedSurface === s ? "rgba(196,147,90,0.12)" : "rgba(128,128,160,0.06)",
                      color: selectedSurface === s ? "var(--ember-bright)" : "var(--fg-secondary)",
                      border: `1px solid ${selectedSurface === s ? "var(--ember)" : "var(--border)"}`,
                    }}
                  >
                    {localizeSurface(s, locale)}
                  </button>
                ))}
              </div>
            </div>
          )}
        </aside>

        {/* Products Grid Section */}
        <section className="lg:col-span-9 flex flex-col gap-8">
          {selectedSeries !== "all" && <SeriesCatalogBanner series={selectedSeries} locale={locale} collections={collections} />}

          {activeFilters.length > 0 ? (
            <div className="flex flex-wrap items-center gap-2" aria-label={t("catalog.active_filters")}>
              <span className="mr-1 text-[10px] uppercase tracking-[0.17em] text-fg-muted">{t("catalog.active_filters")}</span>
              {activeFilters.map((filter) => (
                <button key={filter.key} type="button" onClick={filter.clear} className="flex min-h-11 items-center gap-2 rounded-full border border-ember/35 bg-ember/8 px-4 text-xs text-ember-bright" aria-label={t("catalog.remove_filter", { filter: filter.label })}>{filter.label}<X size={13} /></button>
              ))}
            </div>
          ) : null}

          {/* Top Bar: Search & Result Counter */}
          <div className="flex flex-col sm:flex-row items-center justify-between gap-4 liquid-glass p-4 rounded-2xl" style={{ border: "1px solid var(--border)" }}>
            <span className="text-xs font-mono tracking-wider" style={{ color: "var(--fg-secondary)" }} role="status" aria-live="polite" aria-atomic="true">
              {t("catalog.results", { count: filteredProducts.length })}
            </span>
            <div className="relative w-full sm:w-72">
              <Search size={14} className="absolute left-3.5 top-1/2 -translate-y-1/2" style={{ color: "var(--fg-muted)" }} />
              <input
                type="text"
                aria-label={t("catalog.search")}
                placeholder={t("catalog.search")}
                value={searchQuery}
                onChange={(e) => updateParams({ q: e.target.value.trimStart() || null }, true)}
                className="min-h-11 w-full rounded-full py-2 pl-9 pr-12 text-xs transition-all focus:outline-none focus:ring-2 focus:ring-ember/60"
                style={{
                  background: "rgba(128,128,160,0.06)",
                  border: "1px solid var(--border)",
                  color: "var(--fg-primary)",
                }}
              />
              {searchQuery ? (
                <button type="button" onClick={() => updateParams({ q: null }, true)} className="absolute right-0 top-1/2 flex h-11 w-11 -translate-y-1/2 items-center justify-center rounded-full text-fg-muted transition-colors hover:text-ember focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ember" aria-label={t("catalog.clear_search")}>
                  <X size={15} />
                </button>
              ) : null}
            </div>
          </div>

          {/* Cards Grid */}
          {filteredProducts.length > 0 ? (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
              <AnimatePresence mode="popLayout">
                {filteredProducts.map((product, productIndex) => {
                  const mainImage = product.images[0]?.url;
                  const localizedName = localizeProductName(product, locale);
                  const formatLabels = getProductFormatLabels(product, locale);
                  return (
                    <motion.div
                      layout={!reduceMotion}
                      initial={reduceMotion ? false : { opacity: 0, scale: 0.95 }}
                      animate={{ opacity: 1, scale: 1 }}
                      exit={reduceMotion ? undefined : { opacity: 0, scale: 0.95 }}
                      transition={{ duration: reduceMotion ? 0 : 0.3 }}
                      key={product.id}
                      className="group overflow-hidden rounded-3xl border liquid-glass transition-[border-color,box-shadow,transform] duration-300 hover:scale-[1.02] focus-within:border-ember focus-within:shadow-[0_0_0_3px_color-mix(in_srgb,var(--ember)_20%,transparent)] motion-reduce:transition-none motion-reduce:hover:scale-100"
                      style={{ border: "1px solid var(--border)" }}
                    >
                      <IntentLink href={`/${locale}/products/${product.slug}`} aria-label={`${localizedName} — ${t("featured.details")}`} className="flex h-full flex-col rounded-3xl outline-none focus-visible:ring-2 focus-visible:ring-ember focus-visible:ring-offset-4 focus-visible:ring-offset-surface-0">
                        {/* Image Area */}
                        <div className="relative flex aspect-[4/3] w-full items-center justify-center overflow-hidden p-6" style={{ background: "var(--surface-1)" }}>
                          <ProductCardImage
                            src={mainImage}
                            alt={localizedName}
                            priority={productIndex < 3}
                            unavailableLabel={t("catalog.image_unavailable")}
                            missingLabel={t("catalog.no_image")}
                          />
                        </div>

                        {/* Content Area */}
                        <div className="flex flex-grow flex-col gap-3 p-6">
                          <span className="text-[10px] font-mono uppercase tracking-widest" style={{ color: "var(--ember)" }}>
                            {product.series?.name ? `${localizeSeriesName(product.series.name)} ${t("featured.series_suffix")}` : product.category.name}
                          </span>
                          <h3 className="line-clamp-2 min-h-[3rem] font-serif text-lg font-normal leading-6 tracking-tight" style={{ color: "var(--fg-primary)" }}>
                            {localizedName}
                          </h3>

                          {/* Specs Badges */}
                          <div className="my-1 flex min-h-14 content-start flex-wrap gap-1.5">
                          {product.widthCm && (
                            <span className="px-2.5 py-1 rounded-full text-[10px] font-mono" style={{ background: "rgba(128,128,160,0.08)", color: "var(--fg-secondary)" }}>
                              {product.widthCm} {widthUnit}
                            </span>
                          )}
                          {formatLabels.map((label) => (
                            <span key={label} className="px-2.5 py-1 rounded-full text-[10px] font-mono" style={{ background: "rgba(128,128,160,0.08)", color: "var(--fg-secondary)" }}>
                              {label}
                            </span>
                          ))}
                          {product.burnerCount && (
                            <span className="px-2.5 py-1 rounded-full text-[10px] font-mono" style={{ background: "rgba(128,128,160,0.08)", color: "var(--fg-secondary)" }}>
                              {t("catalog.burners", { count: product.burnerCount })}
                            </span>
                          )}
                          </div>

                          <p className="line-clamp-2 min-h-10 text-xs leading-relaxed" style={{ color: "var(--fg-secondary)" }}>
                            {localizeProductDescription(product, locale)}
                          </p>

                          <div className="mt-auto flex items-center justify-between border-t pt-4" style={{ borderColor: "var(--border)" }}>
                            <span className="flex items-center gap-2 text-xs font-mono font-semibold uppercase tracking-wider transition-colors group-hover:text-ember" style={{ color: "var(--fg-primary)" }}>
                              {t("featured.details")}
                              <ArrowRight size={13} className="transform transition-transform group-hover:translate-x-1 motion-reduce:transition-none motion-reduce:group-hover:translate-x-0" />
                            </span>
                          </div>
                        </div>
                      </IntentLink>
                    </motion.div>
                  );
                })}
              </AnimatePresence>
            </div>
          ) : (
            <div className="liquid-glass rounded-3xl p-10 text-center flex flex-col items-center gap-4 md:p-16" style={{ border: "1px solid var(--border)" }} role="status" aria-live="polite">
              <h3 className="font-serif text-2xl font-light" style={{ color: "var(--fg-primary)" }}>{t("catalog.not_found_title")}</h3>
              <p className="text-xs max-w-sm" style={{ color: "var(--fg-secondary)", lineHeight: "var(--leading-loose)" }}>
                {t("catalog.not_found_desc")}
              </p>
              <button
                onClick={handleResetFilters}
                className="glass-pill px-6 py-3 rounded-full text-xs font-mono uppercase tracking-widest"
                style={{ color: "var(--ember)" }}
              >
                {t("catalog.reset_filters")}
              </button>
            </div>
          )}
        </section>
      </div>
    </div>
  );
}

function ProductCardImage({ src, alt, priority, unavailableLabel, missingLabel }: { src?: string; alt: string; priority: boolean; unavailableLabel: string; missingLabel: string }) {
  const [failed, setFailed] = useState(false);

  if (!src || failed) {
    return (
      <div className="flex flex-col items-center gap-2 px-4 text-center text-fg-muted" role="img" aria-label={failed ? unavailableLabel : missingLabel}>
        <ImageIcon size={28} />
        <span className="text-[10px] uppercase tracking-[0.14em]">{failed ? unavailableLabel : missingLabel}</span>
      </div>
    );
  }

  return (
    <Image
      src={src}
      alt={alt}
      fill
      loading={priority ? "eager" : "lazy"}
      fetchPriority={priority ? "high" : "auto"}
      className="object-contain p-4 transition-transform duration-500 group-hover:scale-105 motion-reduce:transition-none motion-reduce:group-hover:scale-100"
      sizes="(max-width: 768px) 100vw, 33vw"
      onError={() => setFailed(true)}
    />
  );
}
