import { createFileRoute } from "@tanstack/react-router";
import { useMemo, useState, type ReactNode } from "react";
import { SiteFooter } from "@/components/layout/site-footer";
import { SiteHeader } from "@/components/layout/site-header";
import { ProductCard } from "@/components/store/product-card";
import { PRODUCTS } from "@/lib/catalog";
import { LIBRARIES, type LibrarySlug } from "@/lib/libraries";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/store")({ component: StorePage });

function StorePage() {
  const [filter, setFilter] = useState<LibrarySlug | "all">("all");
  const works = useMemo(
    () => (filter === "all" ? PRODUCTS : PRODUCTS.filter((p) => p.library === filter)),
    [filter],
  );

  return (
    <div className="min-h-dvh bg-bg text-fg">
      <SiteHeader />
      <main className="mx-auto max-w-6xl px-4 py-10 sm:px-6">
        <p className="text-[11px] uppercase tracking-[0.2em] text-subtle">The table of works</p>
        <h1 className="mt-2 font-display text-4xl sm:text-5xl">Store</h1>
        <p className="mt-3 max-w-xl text-muted">
          Prints, studies, and two unique paintings. Editions ship flat. Originals leave the west wall.
        </p>
        <div className="mt-8 flex gap-2 overflow-x-auto pb-2">
          <FilterChip active={filter === "all"} onClick={() => setFilter("all")}>
            All
          </FilterChip>
          {LIBRARIES.map((lib) => (
            <FilterChip
              key={lib.slug}
              active={filter === lib.slug}
              onClick={() => setFilter(lib.slug)}
            >
              {lib.name}
            </FilterChip>
          ))}
        </div>
        <div className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {works.map((product) => (
            <ProductCard key={product.id} product={product} />
          ))}
        </div>
      </main>
      <SiteFooter />
    </div>
  );
}

function FilterChip({
  active,
  onClick,
  children,
}: {
  active: boolean;
  onClick: () => void;
  children: ReactNode;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={cn(
        "h-11 shrink-0 rounded-full px-4 text-sm",
        active ? "bg-accent text-accent-fg" : "border border-border bg-bg-elevated text-muted",
      )}
    >
      {children}
    </button>
  );
}
