"use client";

import { useSearchParams } from "next/navigation";
import { Suspense, useDeferredValue, useEffect, useMemo, useState } from "react";
import { ProductCard } from "@/components/product/ProductCard";
import { ShopToolbar } from "@/components/shop/ShopToolbar";
import { PageShell } from "@/components/layout/PageShell";
import { Reveal } from "@/components/motion/Reveal";
import { Stagger, StaggerItem } from "@/components/motion/Stagger";
import { Pagination } from "@/components/ui/Pagination";
import { ProductGridSkeleton } from "@/components/ui/Skeleton";
import type { Product } from "@/data/types";
import { filterProducts, paginate, type SortOption } from "@/lib/products";

function ShopContent() {
  const searchParams = useSearchParams();
  const [catalog, setCatalog] = useState<Product[]>([]);
  const [query, setQuery] = useState(searchParams.get("q") ?? "");
  const [category, setCategory] = useState(searchParams.get("category") ?? "all");
  const [sort, setSort] = useState<SortOption>(
    (searchParams.get("sort") as SortOption) || "featured",
  );
  const [inStock, setInStock] = useState(false);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const deferredQuery = useDeferredValue(query);

  useEffect(() => {
    void fetch("/api/products")
      .then((res) => res.json())
      .then((data: { products?: Product[] }) => setCatalog(data.products ?? []));
  }, []);

  useEffect(() => {
    const q = searchParams.get("q");
    if (q) setQuery(q);
    const c = searchParams.get("category");
    if (c) setCategory(c);
    const s = searchParams.get("sort") as SortOption | null;
    if (s) setSort(s);
  }, [searchParams]);

  const filtered = useMemo(
    () =>
      filterProducts(catalog, {
        query: deferredQuery,
        category,
        sort,
        inStock,
      }),
    [catalog, deferredQuery, category, sort, inStock],
  );

  const paged = useMemo(() => paginate(filtered, page, 24), [filtered, page]);

  const update = (fn: () => void) => {
    setLoading(true);
    fn();
    window.setTimeout(() => setLoading(false), 220);
  };

  return (
    <PageShell
      crumbs={[{ label: "Home", href: "/" }, { label: "Shop" }]}
      eyebrow="BhoFit"
      title="The edit"
      description="Women, men, kids, and baby — cuts with color, size, and honest prices."
    >
      <Reveal>
        <ShopToolbar
          query={query}
          category={category}
          sort={sort}
          inStock={inStock}
          onQuery={(value) =>
            update(() => {
              setQuery(value);
              setPage(1);
            })
          }
          onCategory={(value) =>
            update(() => {
              setCategory(value);
              setPage(1);
            })
          }
          onSort={(value) =>
            update(() => {
              setSort(value);
              setPage(1);
            })
          }
          onInStock={(value) =>
            update(() => {
              setInStock(value);
              setPage(1);
            })
          }
        />
      </Reveal>

      <p className="mt-6 text-sm text-muted">
        Showing {paged.items.length} of {filtered.length} styles
      </p>

      <div className="mt-5">
        {loading ? (
          <ProductGridSkeleton count={24} />
        ) : paged.items.length === 0 ? (
          <p className="border border-border bg-card px-4 py-10 text-center text-sm text-muted">
            No products match these filters. Clear filters to browse the full
            collection.
          </p>
        ) : (
          <Stagger className="product-grid">
            {paged.items.map((product, index) => (
              <StaggerItem key={product.id}>
                <ProductCard product={product} index={index} />
              </StaggerItem>
            ))}
          </Stagger>
        )}
      </div>

      <Pagination
        page={paged.page}
        totalPages={paged.totalPages}
        onChange={setPage}
      />
    </PageShell>
  );
}

export default function ShopPage() {
  return (
    <Suspense fallback={<ProductGridSkeleton count={24} />}>
      <ShopContent />
    </Suspense>
  );
}
