import { useState, useMemo } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { Star, Truck, SlidersHorizontal, X } from "lucide-react";
import Header from "@/components/Header";
import Footer from "@/components/Footer";
import { products, categories } from "@/lib/data";

const sortOptions = [
  { label: "Featured", value: "featured" },
  { label: "Price: Low to High", value: "price-asc" },
  { label: "Price: High to Low", value: "price-desc" },
  { label: "Top Rated", value: "rating" },
  { label: "Newest", value: "newest" },
];

const StarRating = ({ rating }: { rating: number }) => (
  <div className="flex items-center gap-0.5">
    {[1, 2, 3, 4, 5].map((star) => (
      <Star
        key={star}
        className={`w-3.5 h-3.5 ${
          star <= Math.floor(rating)
            ? "fill-[#f39c12] text-[#f39c12]"
            : "text-[#555]"
        }`}
      />
    ))}
  </div>
);

const Products = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const activeCategory = searchParams.get("category") || "all";
  const [sort, setSort] = useState("featured");
  const [filtersOpen, setFiltersOpen] = useState(false);

  const filteredProducts = useMemo(() => {
    let result = [...products];
    if (activeCategory !== "all") {
      result = result.filter((p) => p.categorySlug === activeCategory);
    }
    switch (sort) {
      case "price-asc":
        result.sort((a, b) => a.price - b.price);
        break;
      case "price-desc":
        result.sort((a, b) => b.price - a.price);
        break;
      case "rating":
        result.sort((a, b) => b.rating - a.rating);
        break;
      default:
        break;
    }
    return result;
  }, [activeCategory, sort]);

  const handleCategoryChange = (slug: string) => {
    if (slug === "all") {
      searchParams.delete("category");
    } else {
      searchParams.set("category", slug);
    }
    setSearchParams(searchParams);
  };

  return (
    <div className="min-h-screen bg-[#1a1a1a]">
      <Header />

      {/* Hero Banner */}
      <section className="pt-20 lg:pt-24 pb-10 bg-[#222]">
        <div className="max-w-[1400px] mx-auto px-4 sm:px-6 lg:px-8">
          <p className="font-oswald text-[#d35400] text-sm uppercase tracking-[0.4em] mb-2">
            Our Collection
          </p>
          <h1 className="font-playfair text-3xl sm:text-4xl lg:text-5xl font-bold text-white mb-3">
            {activeCategory === "all"
              ? "All Products"
              : categories.find((c) => c.slug === activeCategory)?.name || "Products"}
          </h1>
          <p className="font-inter text-[#b0b0b0] text-base max-w-2xl">
            {filteredProducts.length} products available. Premium outdoor cooking equipment trusted by pitmasters worldwide.
          </p>
        </div>
      </section>

      <div className="max-w-[1400px] mx-auto px-4 sm:px-6 lg:px-8 py-10">
        <div className="flex flex-col lg:flex-row gap-8">
          {/* Sidebar Filters - Desktop */}
          <aside className="hidden lg:block w-64 shrink-0">
            <div className="sticky top-24">
              <h3 className="font-oswald text-lg font-bold text-white uppercase tracking-wider mb-4">
                Categories
              </h3>
              <ul className="space-y-1">
                <li>
                  <button
                    onClick={() => handleCategoryChange("all")}
                    className={`w-full text-left font-inter text-sm px-3 py-2 rounded transition-colors ${
                      activeCategory === "all"
                        ? "bg-[#d35400] text-white"
                        : "text-[#b0b0b0] hover:text-white hover:bg-[#2b2b2b]"
                    }`}
                  >
                    All Products ({products.length})
                  </button>
                </li>
                {categories.map((cat) => (
                  <li key={cat.slug}>
                    <button
                      onClick={() => handleCategoryChange(cat.slug)}
                      className={`w-full text-left font-inter text-sm px-3 py-2 rounded transition-colors ${
                        activeCategory === cat.slug
                          ? "bg-[#d35400] text-white"
                          : "text-[#b0b0b0] hover:text-white hover:bg-[#2b2b2b]"
                      }`}
                    >
                      {cat.name} ({cat.count})
                    </button>
                  </li>
                ))}
              </ul>

              <div className="mt-8 p-4 bg-[#2b2b2b] border border-[#444] rounded-lg">
                <h4 className="font-oswald text-sm font-bold text-white uppercase tracking-wider mb-2">
                  Need Help?
                </h4>
                <p className="font-inter text-xs text-[#888] mb-3">
                  Our BBQ specialists are here to help you find the perfect grill.
                </p>
                <Link
                  to="/contact"
                  className="font-oswald text-xs text-[#d35400] hover:text-[#e67e22] uppercase tracking-wider transition-colors"
                >
                  Contact Us →
                </Link>
              </div>
            </div>
          </aside>

          {/* Mobile Filter Toggle */}
          <div className="lg:hidden flex items-center justify-between mb-4">
            <button
              onClick={() => setFiltersOpen(true)}
              className="flex items-center gap-2 font-oswald text-sm text-[#b0b0b0] border border-[#444] px-4 py-2 rounded hover:border-[#d35400] transition-colors"
            >
              <SlidersHorizontal className="w-4 h-4" />
              Filters
            </button>
            <select
              value={sort}
              onChange={(e) => setSort(e.target.value)}
              className="bg-[#2b2b2b] border border-[#444] text-[#b0b0b0] font-inter text-sm px-3 py-2 rounded focus:outline-none focus:border-[#d35400]"
            >
              {sortOptions.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>
          </div>

          {/* Mobile Filters Drawer */}
          {filtersOpen && (
            <div className="fixed inset-0 z-50 lg:hidden">
              <div className="absolute inset-0 bg-black/60" onClick={() => setFiltersOpen(false)} />
              <div className="absolute left-0 top-0 bottom-0 w-72 bg-[#1a1a1a] border-r border-[#444] p-6 overflow-y-auto">
                <div className="flex items-center justify-between mb-6">
                  <h3 className="font-oswald text-lg font-bold text-white uppercase">Filters</h3>
                  <button onClick={() => setFiltersOpen(false)} className="text-[#888] hover:text-white">
                    <X className="w-5 h-5" />
                  </button>
                </div>
                <ul className="space-y-1">
                  <li>
                    <button
                      onClick={() => { handleCategoryChange("all"); setFiltersOpen(false); }}
                      className={`w-full text-left font-inter text-sm px-3 py-2 rounded transition-colors ${
                        activeCategory === "all" ? "bg-[#d35400] text-white" : "text-[#b0b0b0] hover:bg-[#2b2b2b]"
                      }`}
                    >
                      All Products
                    </button>
                  </li>
                  {categories.map((cat) => (
                    <li key={cat.slug}>
                      <button
                        onClick={() => { handleCategoryChange(cat.slug); setFiltersOpen(false); }}
                        className={`w-full text-left font-inter text-sm px-3 py-2 rounded transition-colors ${
                          activeCategory === cat.slug ? "bg-[#d35400] text-white" : "text-[#b0b0b0] hover:bg-[#2b2b2b]"
                        }`}
                      >
                        {cat.name}
                      </button>
                    </li>
                  ))}
                </ul>
              </div>
            </div>
          )}

          {/* Product Grid */}
          <div className="flex-1">
            {/* Sort - Desktop */}
            <div className="hidden lg:flex items-center justify-between mb-6">
              <p className="font-inter text-sm text-[#888]">
                Showing {filteredProducts.length} products
              </p>
              <select
                value={sort}
                onChange={(e) => setSort(e.target.value)}
                className="bg-[#2b2b2b] border border-[#444] text-[#b0b0b0] font-inter text-sm px-3 py-2 rounded focus:outline-none focus:border-[#d35400]"
              >
                {sortOptions.map((opt) => (
                  <option key={opt.value} value={opt.value}>
                    {opt.label}
                  </option>
                ))}
              </select>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-6">
              {filteredProducts.map((product) => (
                <Link
                  key={product.id}
                  to={`/products/${product.slug}`}
                  className="group bg-[#2b2b2b] border border-[#444] rounded-lg overflow-hidden transition-all duration-500 hover:-translate-y-2 hover:shadow-[0_12px_40px_rgba(211,84,0,0.15)] hover:border-[#d35400]/50"
                >
                  <div className="relative aspect-[4/3] overflow-hidden">
                    <img
                      src={product.image}
                      alt={product.name}
                      className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105"
                      loading="lazy"
                    />
                    {product.badge && (
                      <span className="absolute top-3 left-3 bg-[#d35400] text-white font-oswald text-xs font-semibold uppercase tracking-wider px-3 py-1 rounded">
                        {product.badge}
                      </span>
                    )}
                  </div>
                  <div className="p-5">
                    <p className="font-oswald text-xs text-[#d35400] uppercase tracking-widest mb-1">
                      {product.category}
                    </p>
                    <h3 className="font-playfair text-lg font-bold text-white mb-2 leading-tight group-hover:text-[#d35400] transition-colors">
                      {product.name}
                    </h3>
                    <div className="flex items-center gap-2 mb-3">
                      <StarRating rating={product.rating} />
                      <span className="font-inter text-sm text-[#b0b0b0]">
                        {product.rating} ({product.reviews})
                      </span>
                    </div>
                    <div className="flex items-baseline gap-2 mb-3">
                      <span className="font-oswald text-2xl font-bold text-white">
                        ${product.price.toLocaleString()}
                      </span>
                      {product.originalPrice && (
                        <span className="font-inter text-sm text-[#888] line-through">
                          ${product.originalPrice.toLocaleString()}
                        </span>
                      )}
                    </div>
                    <div className="flex flex-wrap items-center gap-2">
                      {product.inStock && (
                        <span className="inline-flex items-center gap-1 text-[#27ae60] text-xs font-semibold">
                          <span className="w-2 h-2 bg-[#27ae60] rounded-full" />
                          In Stock
                        </span>
                      )}
                      {product.freeShipping && (
                        <span className="inline-flex items-center gap-1 text-[#d35400] border border-[#d35400] text-xs font-semibold px-2 py-0.5 rounded">
                          <Truck className="w-3 h-3" />
                          Free Shipping
                        </span>
                      )}
                    </div>
                  </div>
                </Link>
              ))}
            </div>

            {filteredProducts.length === 0 && (
              <div className="text-center py-20">
                <p className="font-playfair text-2xl text-white mb-2">No products found</p>
                <p className="font-inter text-[#888]">Try selecting a different category.</p>
              </div>
            )}
          </div>
        </div>
      </div>

      <Footer />
    </div>
  );
};

export default Products;