import { createFileRoute } from "@tanstack/react-router";
import { motion } from "framer-motion";
import { useState, useMemo, useEffect } from "react";
import { FadeIn } from "@/components/motion/FadeIn";
import { StaggerContainer } from "@/components/motion/StaggerContainer";
import { StaggerItem } from "@/components/motion/StaggerItem";
import { products as staticProducts, type Product } from "@/data/products";
import { fetchProducts } from "@/lib/api";
import { SITE_URL } from "@/lib/site";

export const Route = createFileRoute("/_site/products")({
  head: () => ({
    meta: [
      { title: "Products — PVC Pipes, Junction Boxes & MCB Boxes | Komal Star" },
      {
        name: "description",
        content:
          "Explore Komal Star's complete range of ISI-certified PVC conduit pipes, flexible pipes, junction boxes, concealed boxes and MCB TPN distribution boxes.",
      },
      { property: "og:title", content: "Komal Star Product Catalog" },
      { property: "og:description", content: "Premium electrical wiring accessories — wholesale across Rajasthan." },
      { property: "og:type", content: "website" },
      { property: "og:url", content: `${SITE_URL}/products` },
    ],
    links: [{ rel: "canonical", href: `${SITE_URL}/products` }],
  }),
  component: ProductsPage,
});

function ProductsPage() {
  const [products, setProducts] = useState<Product[]>(staticProducts);
  useEffect(() => {
    fetchProducts().then(setProducts).catch(() => {});
  }, []);
  const categories = useMemo(
    () => ["All", ...Array.from(new Set(products.map((p) => p.category)))],
    [products],
  );
  const [active, setActive] = useState("All");
  const filtered = active === "All" ? products : products.filter((p) => p.category === active);

  return (
    <div>
      <section className="relative overflow-hidden bg-mesh pt-20 pb-12 md:pt-28 md:pb-16">
        <div className="mx-auto max-w-7xl px-6 text-center">
          <FadeIn>
            <span className="text-xs font-semibold uppercase tracking-[0.2em] text-primary">
              Catalog · 2026
            </span>
          </FadeIn>
          <FadeIn delay={0.1}>
            <h1 className="mt-4 font-display text-5xl font-bold md:text-7xl">
              Our <span className="text-gradient-sky">complete</span> product range.
            </h1>
          </FadeIn>
          <FadeIn delay={0.2}>
            <p className="mx-auto mt-6 max-w-2xl text-lg text-muted-foreground">
              Every product built from certified materials, tested for real-site conditions.
            </p>
          </FadeIn>
        </div>
      </section>

      {/* Filter */}
      <section className="sticky top-20 z-30 border-y border-border/40 bg-white/70 py-4 backdrop-blur-xl">
        <div className="mx-auto flex max-w-7xl flex-wrap gap-2 overflow-x-auto px-6">
          {categories.map((c) => (
            <button
              key={c}
              onClick={() => setActive(c)}
              className={`relative rounded-full px-5 py-2 text-sm font-medium transition-colors ${
                active === c ? "text-primary-foreground" : "text-foreground/70 hover:text-primary"
              }`}
            >
              {active === c && (
                <motion.span
                  layoutId="cat-pill"
                  className="absolute inset-0 rounded-full bg-primary"
                  transition={{ type: "spring", stiffness: 380, damping: 30 }}
                />
              )}
              <span className="relative">{c}</span>
            </button>
          ))}
        </div>
      </section>

      <section className="mx-auto max-w-7xl px-6 py-16">
        <StaggerContainer key={active} className="grid gap-8 md:grid-cols-2 lg:grid-cols-3" stagger={0.08}>
          {filtered.map((p) => (
            <StaggerItem key={p.slug}>
              <motion.article
                whileHover={{ y: -8 }}
                transition={{ type: "spring", stiffness: 300, damping: 20 }}
                className="group flex h-full flex-col overflow-hidden rounded-3xl border border-border/60 bg-white shadow-sm"
              >
                <div className="relative aspect-[4/3] overflow-hidden bg-sky-soft/40">
                  <motion.img
                    src={p.image}
                    alt={p.name}
                    loading="lazy"
                    className="h-full w-full object-cover"
                    whileHover={{ scale: 1.08 }}
                    transition={{ duration: 0.6 }}
                  />
                  <div className="absolute left-4 top-4 rounded-full bg-white/90 px-3 py-1 text-[10px] font-semibold uppercase tracking-widest text-primary backdrop-blur">
                    {p.category}
                  </div>
                </div>
                <div className="flex flex-1 flex-col p-6">
                  <h3 className="font-display text-xl font-semibold">{p.name}</h3>
                  <p className="mt-1 text-sm text-primary">{p.tagline}</p>
                  <p className="mt-3 text-sm leading-relaxed text-muted-foreground">{p.description}</p>
                  <ul className="mt-5 flex flex-wrap gap-2">
                    {p.specs.map((s) => (
                      <li
                        key={s}
                        className="rounded-full bg-sky-soft px-3 py-1 text-xs font-medium text-sky-deep"
                      >
                        {s}
                      </li>
                    ))}
                  </ul>
                </div>
              </motion.article>
            </StaggerItem>
          ))}
        </StaggerContainer>
      </section>
    </div>
  );
}
