"use client";
import {useState, useEffect, Suspense} from "react";
import Link from "next/link";
import Image from "next/image";
import products from "@/lib/data/products.json";
import {useSearchParams, useRouter} from "next/navigation";

// Wrap the main component with Suspense
export default function AllProducts() {
  return (
    <Suspense fallback={<div className="min-h-screen">Loading products...</div>}>
      <ProductsContent />
    </Suspense>
  );
}

// Split the content into a separate component that uses searchParams
function ProductsContent() {
  const router = useRouter();
  const searchParams = useSearchParams();

  // Get initial states from URL or defaults
  const initialType = searchParams.get("types")?.replace(/-/g, " ") || products[0]?.types || "Office Furniture";
  const initialCategory = searchParams.get("category") || "All";
  const initialBrand = searchParams.get("brand") || "All";

  // State management
  const [selectedTypes, setSelectedTypes] = useState(initialType);
  const [selectedCategory, setSelectedCategory] = useState(initialCategory);
  const [selectedBrand, setSelectedBrand] = useState(initialBrand);
  const [isMobileFilterOpen, setIsMobileFilterOpen] = useState(false);

  // Update URL when filters change
  const updateURL = () => {
    const params = new URLSearchParams();
    params.set("types", selectedTypes.replace(/ /g, "-"));
    if (selectedCategory !== "All") params.set("category", selectedCategory);
    if (selectedBrand !== "All") params.set("brand", selectedBrand);
    router.push(`/products?${params.toString()}`);
  };

  // Sync state with URL parameters
  useEffect(() => {
    const typeParam = searchParams.get("types")?.replace(/-/g, " ");
    const categoryParam = searchParams.get("category");
    const brandParam = searchParams.get("brand");

    if (typeParam) setSelectedTypes(typeParam);
    if (categoryParam) setSelectedCategory(categoryParam || "All");
    if (brandParam) setSelectedBrand(brandParam || "All");
  }, [searchParams]);

  // Update URL when filters change
  useEffect(() => {
    updateURL();
  }, [selectedTypes, selectedCategory, selectedBrand]);

  // Filter options
  const types = [...new Set(products.map((p) => p.types))];
  const categories = ["All", ...new Set(products.filter((p) => p.types === selectedTypes).map((p) => p.category))];
  const brands = ["All", ...new Set(products.filter((p) => p.types === selectedTypes && (selectedCategory === "All" || p.category === selectedCategory)).map((p) => p.brand))];

  // Filtered products
  const filteredProducts = products.filter((p) => p.types === selectedTypes && (selectedCategory === "All" || p.category === selectedCategory) && (selectedBrand === "All" || p.brand === selectedBrand));

  // Mobile filter handlers
  const handleMobileTypeChange = (type) => {
    setSelectedTypes(type);
    setSelectedCategory("All");
    setSelectedBrand("All");
    setIsMobileFilterOpen(false);
  };

  const handleMobileCategoryChange = (category) => {
    setSelectedCategory(category);
    setSelectedBrand("All");
  };

  const handleMobileBrandChange = (brand) => {
    setSelectedBrand(brand);
  };

  return (
    <section className="mb-10 w-full">
      <div className="mx-auto max-w-screen-2xl px-5 py-10 sm:px-8 lg:px-10 lg:py-16">
        <div className="grid grid-cols-1 gap-10 lg:grid-cols-4">
          {/* Desktop Filter Sidebar */}
          <div className="hidden flex-col lg:flex">
            {types.map((type) => (
              <button
                key={type}
                onClick={() => {
                  setSelectedTypes(type);
                  setSelectedCategory("All");
                  setSelectedBrand("All");
                }}
                className={`rounded-lg p-3 text-left font-semibold ${selectedTypes === type ? "bg-slate-100" : ""}`}>
                {type}
              </button>
            ))}

            <div className="h-px w-full bg-slate-200 my-3"></div>

            <span className="text-sm py-3">By Category</span>
            {categories.map((category) => (
              <button key={category} onClick={() => setSelectedCategory(category)} className={`rounded-lg p-3 text-left text-sm font-semibold ${selectedCategory === category ? "bg-slate-100" : ""}`}>
                {category}
              </button>
            ))}

            <span className="text-sm py-3">By Brands</span>
            {brands.map((brand) => (
              <button key={brand} onClick={() => setSelectedBrand(brand)} className={`rounded-lg p-3 text-left text-sm font-semibold ${selectedBrand === brand ? "bg-slate-100" : ""}`}>
                {brand}
              </button>
            ))}
          </div>

          {/* Mobile Filter Panel */}
          <div className={`fixed inset-0 z-30 bg-white transition-transform duration-300 overflow-y-auto ${isMobileFilterOpen ? "translate-x-0" : "translate-x-full"} lg:hidden`}>
            <div className="flex justify-between items-center p-4 border-b">
              <span className="text-lg font-semibold">Filter</span>
              <button onClick={() => setIsMobileFilterOpen(false)} className="text-2xl">
                ✕
              </button>
            </div>
            <div className="p-4 flex flex-col">
              <span className="text-lg font-semibold mb-4">Product Types</span>
              {types.map((type) => (
                <button key={type} onClick={() => handleMobileTypeChange(type)} className={`rounded-lg p-3 text-left font-semibold ${selectedTypes === type ? "bg-slate-100" : ""}`}>
                  {type}
                </button>
              ))}

              <div className="h-px w-full bg-slate-200 my-4"></div>

              <span className="text-lg font-semibold mb-4">Categories</span>
              {categories.map((category) => (
                <button key={category} onClick={() => handleMobileCategoryChange(category)} className={`rounded-lg p-3 text-left text-sm font-semibold ${selectedCategory === category ? "bg-slate-100" : ""}`}>
                  {category}
                </button>
              ))}

              <div className="h-px w-full bg-slate-200 my-4"></div>

              <span className="text-lg font-semibold mb-4">Brands</span>
              {brands.map((brand) => (
                <button key={brand} onClick={() => handleMobileBrandChange(brand)} className={`rounded-lg p-3 text-left text-sm font-semibold ${selectedBrand === brand ? "bg-slate-100" : ""}`}>
                  {brand}
                </button>
              ))}
            </div>
          </div>

          {/* Products Section */}
          <div className="flex flex-col gap-6 lg:col-span-3 lg:gap-12">
            {/* Header and Mobile Filter Button */}
            <div className="flex flex-col items-start gap-5">
              <div className="flex lg:hidden flex-row items-center justify-between w-full">
                <span className="text-2xl font-bold">{selectedTypes}</span>
                <button className="rounded-lg border border-slate-300 px-4 py-2 text-sm" onClick={() => setIsMobileFilterOpen(true)}>
                  Filter
                </button>
              </div>

              {/* Breadcrumbs */}
              <div className="flex flex-wrap items-center gap-1 sm:gap-4">
                <span className="text-xs font-medium lg:text-2xl lg:font-bold">{selectedTypes}</span>
                {selectedCategory !== "All" && (
                  <>
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" className="size-4 lg:size-5 shrink-0">
                      <path strokeLinecap="round" strokeLinejoin="round" d="m8.25 4.5 7.5 7.5-7.5 7.5" />
                    </svg>
                    <span className="text-xs font-light lg:text-xl lg:font-medium">{selectedCategory}</span>
                  </>
                )}
                {selectedBrand !== "All" && (
                  <>
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" className="size-4 lg:size-5 shrink-0">
                      <path strokeLinecap="round" strokeLinejoin="round" d="m8.25 4.5 7.5 7.5-7.5 7.5" />
                    </svg>
                    <span className="text-xs font-light lg:text-xl lg:font-medium">{selectedBrand}</span>
                  </>
                )}
              </div>
            </div>

            {/* Product Grid */}
            <div className="grid grid-cols-2 gap-x-3 gap-y-5 sm:gap-10 lg:grid-cols-4">
              {filteredProducts.map((product) => (
                <Link key={product.slug} href={`/products/${product.slug}`} className="group relative flex w-full flex-col gap-2">
                  <div className="flex w-full items-end justify-center bg-white border border-slate-200 rounded-lg overflow-hidden">
                    <Image src={product.images[0]} alt={product.title} width={500} height={500} className="aspect-square w-full shrink-0 origin-center rounded-lg object-contain transition-transform duration-700 ease-in-out group-hover:scale-110" />
                  </div>
                  <div className="mt-2 flex flex-col items-center sm:items-start">
                    <span className="text-center text-base font-semibold group-hover:text-green-500 group-hover:underline sm:text-start">{product.title}</span>
                    <span className="text-xs text-gray-500">{product.category}</span>
                  </div>
                  {product.isNew && <div className="absolute right-3 top-3 h-6 z-20 items-center rounded-md bg-green-500 px-2 text-sm text-white flex">New</div>}
                </Link>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
