"use client";

import { useEffect, useMemo, useState } from "react";
import { useSearchParams } from "next/navigation";
import { motion } from "framer-motion";
import { SlidersHorizontal } from "lucide-react";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import ProductCard from "@/components/ProductCard";
import { useStore } from "@/context/StoreContext";

export default function ProductsPageClient() {
  const { store, catalogProducts, catalogCategories } = useStore();
  const searchParams = useSearchParams();
  const categoryParam = searchParams.get("category");
  const featuredParam = searchParams.get("featured");
  const [activeCategory, setActiveCategory] = useState(categoryParam || "All");
  const [sortBy, setSortBy] = useState("featured");
  const [priceRange, setPriceRange] = useState<[number, number]>([0, 2000]);
  const [isGridLoading, setIsGridLoading] = useState(false);

  useEffect(() => {
    setActiveCategory(categoryParam || "All");
  }, [categoryParam]);

  const triggerGridLoading = () => {
    setIsGridLoading(true);
    window.setTimeout(() => setIsGridLoading(false), 280);
  };

  const activeCategoryRecord = useMemo(
    () =>
      activeCategory === "All"
        ? undefined
        : store.categories.find((category) => category.name === activeCategory),
    [activeCategory, store.categories],
  );
  const categoryCover = activeCategoryRecord?.image || "";

  const baseList =
    featuredParam === "true"
      ? catalogProducts.filter((p) => p.badge === "Featured")
      : catalogProducts;

  const filtered = (activeCategory === "All"
    ? baseList
    : baseList.filter((p) => p.category === activeCategory)
  ).filter((p) => p.price >= priceRange[0] && p.price <= priceRange[1]);

  const sorted = [...filtered].sort((a, b) => {
    if (sortBy === "price-low") return a.price - b.price;
    if (sortBy === "price-high") return b.price - a.price;
    if (sortBy === "rating") return b.rating - a.rating;
    if (sortBy === "newest") return b.reviews - a.reviews;
    return 0;
  });

  return (
    <div className="min-h-screen bg-background">
      <Navbar />

      {activeCategory !== "All" ? (
        <section className="relative isolate overflow-hidden border-b border-border/60">
          <div className="absolute inset-0 bg-gradient-dark" />
          {categoryCover ? (
            <img
              src={categoryCover}
              alt={`${activeCategory} cover`}
              className="absolute inset-0 h-full w-full object-cover"
            />
          ) : null}
          <div className="absolute inset-0 bg-gradient-to-r from-Blue/75 via-Blue/55 to-Blue/25" />
          <div className="container relative mx-auto px-4 py-16 lg:px-8 lg:py-24">
            <motion.div
              key={activeCategory}
              initial={{ opacity: 0, y: 18 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.45, ease: [0.22, 1, 0.36, 1] }}
              className="max-w-2xl text-white"
            >
              <p className="text-xs font-semibold uppercase tracking-[0.2em] text-white/70">Category</p>
              <h1 className="mt-3 text-4xl font-bold lg:text-5xl">{activeCategory}</h1>
              <p className="mt-3 text-sm text-white/75 lg:text-base">
                {sorted.length} product{sorted.length !== 1 && "s"} available
              </p>
            </motion.div>
          </div>
        </section>
      ) : (
        <div className="border-b border-border/60 bg-gradient-warm">
          <div className="container mx-auto px-4 py-10 lg:px-8">
            <motion.div initial={{ opacity: 0, y: 16 }} animate={{ opacity: 1, y: 0 }}>
              <h1 className="text-4xl font-bold lg:text-5xl">All Products</h1>
              <p className="mt-3 text-muted-foreground">
                {sorted.length} product{sorted.length !== 1 && "s"} available
              </p>
            </motion.div>
          </div>
        </div>
      )}

      <motion.div initial={{ opacity: 0, y: 16 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true, amount: 0.2 }} transition={{ duration: 0.45, ease: [0.22, 1, 0.36, 1] }} className="container mx-auto px-4 py-8 lg:px-8">
        <div className="flex flex-col gap-5">
          <div className="flex flex-wrap gap-2">
            {catalogCategories.map((cat) => (
              <button
                key={cat}
                type="button"
                onClick={() => {
                  setActiveCategory(cat);
                  triggerGridLoading();
                }}
                className={`rounded-xl px-4 py-2.5 text-xs font-semibold transition-all duration-200 ${
                  activeCategory === cat
                    ? "bg-primary text-primary-foreground shadow-md"
                    : "border border-border/60 bg-card text-muted-foreground hover:border-accent/40 hover:text-foreground"
                }`}
              >
                {cat}
              </button>
            ))}
          </div>

          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <SlidersHorizontal className="h-4 w-4 text-muted-foreground" />
              <select
                value={sortBy}
                onChange={(e) => {
                  setSortBy(e.target.value);
                  triggerGridLoading();
                }}
                className="rounded-xl border border-border/60 bg-card px-4 py-2.5 text-xs font-medium outline-none focus:border-accent"
              >
                <option value="featured">Featured</option>
                <option value="price-low">Price: Low → High</option>
                <option value="price-high">Price: High → Low</option>
                <option value="rating">Top Rated</option>
                <option value="newest">Most Reviewed</option>
              </select>
            </div>
            <p className="text-xs text-muted-foreground">
              Showing {sorted.length} result{sorted.length !== 1 && "s"}
            </p>
          </div>
        </div>

        {isGridLoading ? (
          <div className="mt-8 grid gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
            {Array.from({ length: 8 }).map((_, idx) => (
              <div key={idx} className="overflow-hidden rounded-2xl border border-border/40 bg-card p-4 shadow-card">
                <div className="aspect-square animate-pulse rounded-xl bg-secondary/70" />
                <div className="mt-4 h-3 w-20 animate-pulse rounded bg-secondary/70" />
                <div className="mt-3 h-4 w-4/5 animate-pulse rounded bg-secondary/70" />
                <div className="mt-2 h-3 w-full animate-pulse rounded bg-secondary/70" />
              </div>
            ))}
          </div>
        ) : (
          <motion.div key={`${activeCategory}-${sortBy}-${sorted.length}`} initial="hidden" animate="show" variants={{ hidden: {}, show: { transition: { staggerChildren: 0.06 } } }} className="mt-8 grid gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
            {sorted.map((p, i) => (
              <motion.div key={p.id} variants={{ hidden: { opacity: 0, y: 22, scale: 0.98 }, show: { opacity: 1, y: 0, scale: 1 } }} transition={{ duration: 0.34, ease: [0.22, 1, 0.36, 1], delay: i * 0.01 }}>
                <ProductCard product={p} index={i} />
              </motion.div>
            ))}
          </motion.div>
        )}

        {sorted.length === 0 && (
          <div className="py-20 text-center">
            <p className="text-xl font-bold">No products found</p>
            <p className="mt-2 text-sm text-muted-foreground">Try changing your filters</p>
            <button type="button" onClick={() => { setActiveCategory("All"); setPriceRange([0, 2000]); }} className="mt-4 text-sm font-semibold text-accent hover:underline">
              Reset Filters
            </button>
          </div>
        )}
      </motion.div>
      <Footer />
    </div>
  );
}
