"use client";

import React, { useState, useMemo, useEffect, Suspense } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { useApp } from "@/context/AppContext";
import { Navbar } from "@/components/Navbar";
import { Footer } from "@/components/Footer";
import { FloatingWhatsApp } from "@/components/FloatingWhatsApp";
import { AIAssistant } from "@/components/AIAssistant";
import { mockProducts, Product } from "@/data/mockData";
import { Heart, Search, SlidersHorizontal, ArrowUpDown, X, Star } from "lucide-react";
import Image from "next/image";
import Link from "next/link";

function ShopContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const { t, formatPrice, addToCart, toggleWishlist, wishlist } = useApp();

  // Filter & Search states
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedCategory, setSelectedCategory] = useState<string>("");
  const [selectedSize, setSelectedSize] = useState<string>("");
  const [selectedColor, setSelectedColor] = useState<string>("");
  const [priceRange, setPriceRange] = useState<number>(12000); // Max PKR
  const [sortOption, setSortOption] = useState<string>("featured");
  const [showMobileFilters, setShowMobileFilters] = useState(false);

  // Sync category from URL search params on load
  useEffect(() => {
    const cat = searchParams.get("category");
    if (cat) {
      setSelectedCategory(cat);
    }
  }, [searchParams]);

  // Unique filters lists derived from products
  const categories = ["Essentials", "Oversized", "Premium Cotton"];
  const sizes = ["S", "M", "L", "XL"];
  const colors = ["Matte Black", "Warm White", "Sand Grey", "Off-White", "Sand Beige", "Charcoal"];

  // Filter and sort computation
  const filteredProducts = useMemo(() => {
    let result = [...mockProducts];

    // Search query filter
    if (searchTerm.trim()) {
      const q = searchTerm.toLowerCase();
      result = result.filter(
        (p) =>
          p.name.toLowerCase().includes(q) ||
          p.description.toLowerCase().includes(q) ||
          p.category.toLowerCase().includes(q)
      );
    }

    // Category filter
    if (selectedCategory) {
      result = result.filter((p) => p.category === selectedCategory);
    }

    // Size filter
    if (selectedSize) {
      result = result.filter((p) => p.sizes.includes(selectedSize));
    }

    // Color filter
    if (selectedColor) {
      result = result.filter((p) => p.colors.includes(selectedColor));
    }

    // Price range filter
    result = result.filter((p) => p.price * (1 - p.discount / 100) <= priceRange);

    // Sorting
    if (sortOption === "price-asc") {
      result.sort((a, b) => {
        const pA = a.price * (1 - a.discount / 100);
        const pB = b.price * (1 - b.discount / 100);
        return pA - pB;
      });
    } else if (sortOption === "price-desc") {
      result.sort((a, b) => {
        const pA = a.price * (1 - a.discount / 100);
        const pB = b.price * (1 - b.discount / 100);
        return pB - pA;
      });
    } else if (sortOption === "best-selling") {
      result.sort((a, b) => b.rating - a.rating);
    } else if (sortOption === "newest") {
      result.reverse();
    }

    return result;
  }, [searchTerm, selectedCategory, selectedSize, selectedColor, priceRange, sortOption]);

  const handleClearFilters = () => {
    setSearchTerm("");
    setSelectedCategory("");
    setSelectedSize("");
    setSelectedColor("");
    setPriceRange(12000);
    setSortOption("featured");
    router.replace("/shop");
  };

  return (
    <div className="flex min-h-screen flex-col bg-[#F8F7F2]">
      <Navbar />

      <main className="flex-1 py-12 px-6 md:px-12 mx-auto max-w-7xl w-full">
        {/* Header section */}
        <div className="mb-10 text-center space-y-2">
          <span className="text-[10px] font-bold tracking-[0.35em] text-[#D4AF37] uppercase">STARBOY LABS</span>
          <h1 className="font-serif text-3xl font-bold uppercase tracking-widest text-[#0a0a0a]">
            EDITORIAL ARCHIVE
          </h1>
          <p className="text-xs text-neutral-500 font-light max-w-md mx-auto">
            Browse our core capsules of heavyweight t-shirts, slouchy hoodies, and technical layering essentials.
          </p>
        </div>

        {/* Toolbar: Search & Sort */}
        <div className="border border-[#1A1A1A]/10 bg-white p-4 flex flex-col sm:flex-row items-center justify-between gap-4 mb-8">
          <div className="relative w-full sm:max-w-xs">
            <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-neutral-400" />
            <input
              type="text"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="Search products, GSM..."
              className="w-full bg-[#F8F7F2] border border-[#1A1A1A]/10 text-xs px-10 py-2.5 outline-none focus:border-[#D4AF37]"
            />
          </div>

          <div className="flex items-center justify-end gap-4 w-full sm:w-auto">
            {/* Sorting Dropdown */}
            <div className="flex items-center gap-2 border border-[#1A1A1A]/10 px-3 py-2 bg-[#F8F7F2]">
              <ArrowUpDown className="w-3.5 h-3.5 text-neutral-600" />
              <select
                value={sortOption}
                onChange={(e) => setSortOption(e.target.value)}
                className="bg-transparent text-[11px] font-bold uppercase outline-none cursor-pointer tracking-wider"
              >
                <option value="featured">Featured</option>
                <option value="newest">New Arrivals</option>
                <option value="best-selling">Best Sellers</option>
                <option value="price-asc">Price: Low to High</option>
                <option value="price-desc">Price: High to Low</option>
              </select>
            </div>

            {/* Mobile Filter Toggle */}
            <button
              onClick={() => setShowMobileFilters(!showMobileFilters)}
              className="lg:hidden border border-[#1A1A1A]/10 px-3 py-2 bg-[#F8F7F2] flex items-center gap-1.5 text-[11px] font-bold uppercase tracking-wider"
            >
              <SlidersHorizontal className="w-3.5 h-3.5" />
              Filters
            </button>
          </div>
        </div>

        {/* Grid Area */}
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
          
          {/* Left Sidebar Filter - Desktop */}
          <aside className="hidden lg:block lg:col-span-3 border border-[#1A1A1A]/10 bg-white p-6 space-y-8">
            <div className="flex items-center justify-between border-b border-[#1A1A1A]/10 pb-4">
              <h3 className="text-xs font-bold uppercase tracking-widest text-[#0a0a0a]">Filters</h3>
              <button
                onClick={handleClearFilters}
                className="text-[9px] font-bold tracking-wider text-[#D4AF37] hover:underline uppercase"
              >
                Clear All
              </button>
            </div>

            {/* Categories */}
            <div className="space-y-3">
              <h4 className="text-[10px] font-bold uppercase tracking-widest text-neutral-400">Categories</h4>
              <div className="flex flex-col gap-1.5">
                {categories.map((cat) => (
                  <button
                    key={cat}
                    onClick={() => setSelectedCategory(selectedCategory === cat ? "" : cat)}
                    className={`text-left text-xs tracking-wide py-1 border-b border-transparent hover:border-[#D4AF37] transition-all ${
                      selectedCategory === cat ? "text-[#D4AF37] font-bold" : "text-[#1a1a1a]"
                    }`}
                  >
                    {cat}
                  </button>
                ))}
              </div>
            </div>

            {/* Size Matrix Selector */}
            <div className="space-y-3">
              <h4 className="text-[10px] font-bold uppercase tracking-widest text-neutral-400">Sizes</h4>
              <div className="grid grid-cols-4 gap-2">
                {sizes.map((sz) => (
                  <button
                    key={sz}
                    onClick={() => setSelectedSize(selectedSize === sz ? "" : sz)}
                    className={`border text-[10px] font-bold py-2 text-center uppercase transition-all ${
                      selectedSize === sz
                        ? "bg-[#0a0a0a] border-black text-[#f8f7f2]"
                        : "border-[#1A1A1A]/10 bg-[#f8f7f2]/40 hover:border-[#D4AF37]"
                    }`}
                  >
                    {sz}
                  </button>
                ))}
              </div>
            </div>

            {/* Colors */}
            <div className="space-y-3">
              <h4 className="text-[10px] font-bold uppercase tracking-widest text-neutral-400">Colors</h4>
              <div className="flex flex-wrap gap-2">
                {colors.map((col) => (
                  <button
                    key={col}
                    onClick={() => setSelectedColor(selectedColor === col ? "" : col)}
                    className={`border text-[9px] font-bold px-3 py-1.5 uppercase transition-all ${
                      selectedColor === col
                        ? "bg-[#0a0a0a] border-black text-[#f8f7f2]"
                        : "border-[#1A1A1A]/10 bg-[#f8f7f2]/40 hover:border-[#D4AF37]"
                    }`}
                  >
                    {col}
                  </button>
                ))}
              </div>
            </div>

            {/* Price Slider */}
            <div className="space-y-3">
              <div className="flex justify-between items-center text-[10px] font-bold uppercase tracking-widest text-neutral-400">
                <span>Max Price</span>
                <span className="text-[#0a0a0a] font-sans text-xs">Rs. {priceRange.toLocaleString()}</span>
              </div>
              <input
                type="range"
                min="2000"
                max="15000"
                step="500"
                value={priceRange}
                onChange={(e) => setPriceRange(Number(e.target.value))}
                className="w-full h-1 bg-neutral-200 accent-[#0a0a0a] outline-none"
              />
            </div>
          </aside>

          {/* Right Product Grid */}
          <section className="lg:col-span-9">
            {filteredProducts.length === 0 ? (
              <div className="border border-[#1A1A1A]/10 bg-white p-16 text-center space-y-4">
                <p className="text-sm text-neutral-400">No products matching the selected filters found.</p>
                <button
                  onClick={handleClearFilters}
                  className="bg-[#0A0A0A] text-white hover:bg-[#D4AF37] hover:text-black font-semibold text-xs tracking-widest px-8 py-3.5 transition-all uppercase"
                >
                  Clear Filters
                </button>
              </div>
            ) : (
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                {filteredProducts.map((product) => (
                  <div
                    key={product.id}
                    className="group border border-[#1A1A1A]/10 bg-white p-4 flex flex-col justify-between hover:shadow-lg transition-all duration-300 relative"
                  >
                    {/* Image */}
                    <div className="relative aspect-[4/5] w-full overflow-hidden bg-neutral-100 mb-4">
                      <Link href={`/product/${product.id}`}>
                        <Image
                          src={product.image}
                          alt={product.name}
                          fill
                          className="object-cover object-center transition-transform duration-700 group-hover:scale-105"
                        />
                        <div className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-500">
                          <Image
                            src={product.hoverImage}
                            alt={product.name}
                            fill
                            className="object-cover object-center"
                          />
                        </div>
                      </Link>

                      {/* Tag */}
                      {product.discount > 0 && (
                        <span className="absolute top-3 left-3 bg-[#D4AF37] text-black text-[8px] font-extrabold px-1.5 py-0.5 tracking-widest uppercase">
                          {product.discount}% OFF
                        </span>
                      )}

                      <button
                        onClick={() => toggleWishlist(product.id)}
                        className="absolute top-3 right-3 h-7 w-7 rounded-full bg-white/80 backdrop-blur-md flex items-center justify-center text-neutral-600 hover:text-red-600 hover:bg-white shadow transition-all duration-200"
                      >
                        <Heart className={`h-4 w-4 ${wishlist.includes(product.id) ? "fill-red-600 text-red-600" : ""}`} />
                      </button>
                    </div>

                    {/* Details */}
                    <div className="space-y-2 flex-1 flex flex-col justify-between">
                      <div>
                        <span className="text-[8px] font-bold text-neutral-400 uppercase tracking-widest block">
                          {product.category} | {product.gsm} GSM
                        </span>
                        <Link href={`/product/${product.id}`} className="hover:text-[#D4AF37] transition-colors">
                          <h3 className="font-serif text-xs font-bold text-[#1A1A1A] leading-snug tracking-wide uppercase">
                            {product.name}
                          </h3>
                        </Link>
                      </div>

                      <div className="pt-2 border-t border-[#1A1A1A]/5 flex items-center justify-between">
                        <div>
                          {product.discount > 0 ? (
                            <div className="flex items-center gap-1.5">
                              <span className="text-xs font-bold text-[#0A0A0A]">
                                {formatPrice(product.price * (1 - product.discount / 100))}
                              </span>
                              <span className="text-[9px] text-neutral-400 line-through">
                                {formatPrice(product.price)}
                              </span>
                            </div>
                          ) : (
                            <span className="text-xs font-bold text-[#0A0A0A]">
                              {formatPrice(product.price)}
                            </span>
                          )}
                        </div>

                        <button
                          onClick={() => addToCart(product, 1, product.sizes[0], product.colors[0])}
                          className="border border-[#1A1A1A] hover:bg-[#0A0A0A] hover:text-white text-[8px] font-bold tracking-widest px-2.5 py-1.5 uppercase transition-all duration-200"
                        >
                          Quick Add
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </section>

        </div>
      </main>

      {/* Mobile Drawer Filters Panel */}
      {showMobileFilters && (
        <div className="fixed inset-0 z-50 flex justify-end">
          {/* overlay */}
          <div
            onClick={() => setShowMobileFilters(false)}
            className="fixed inset-0 bg-black/40 backdrop-blur-xs"
          />
          {/* panel */}
          <div className="relative z-10 w-full max-w-sm h-full bg-white p-6 overflow-y-auto flex flex-col space-y-6">
            <div className="flex items-center justify-between border-b pb-4">
              <h3 className="text-xs font-bold uppercase tracking-widest text-[#0a0a0a]">Filters</h3>
              <button onClick={() => setShowMobileFilters(false)} className="p-1">
                <X className="w-5 h-5 text-neutral-600" />
              </button>
            </div>

            {/* Categories */}
            <div className="space-y-3">
              <h4 className="text-[10px] font-bold uppercase tracking-widest text-neutral-400">Categories</h4>
              <div className="flex flex-col gap-1.5">
                {categories.map((cat) => (
                  <button
                    key={cat}
                    onClick={() => {
                      setSelectedCategory(selectedCategory === cat ? "" : cat);
                      setShowMobileFilters(false);
                    }}
                    className={`text-left text-xs tracking-wide py-1 border-b border-transparent ${
                      selectedCategory === cat ? "text-[#D4AF37] font-bold" : "text-[#1a1a1a]"
                    }`}
                  >
                    {cat}
                  </button>
                ))}
              </div>
            </div>

            {/* Size Selector */}
            <div className="space-y-3">
              <h4 className="text-[10px] font-bold uppercase tracking-widest text-neutral-400">Sizes</h4>
              <div className="grid grid-cols-4 gap-2">
                {sizes.map((sz) => (
                  <button
                    key={sz}
                    onClick={() => {
                      setSelectedSize(selectedSize === sz ? "" : sz);
                      setShowMobileFilters(false);
                    }}
                    className={`border text-[10px] font-bold py-2 text-center uppercase ${
                      selectedSize === sz
                        ? "bg-[#0a0a0a] border-black text-[#f8f7f2]"
                        : "border-[#1A1A1A]/10 bg-[#f8f7f2]/40"
                    }`}
                  >
                    {sz}
                  </button>
                ))}
              </div>
            </div>

            {/* Colors */}
            <div className="space-y-3">
              <h4 className="text-[10px] font-bold uppercase tracking-widest text-neutral-400">Colors</h4>
              <div className="flex flex-wrap gap-2">
                {colors.map((col) => (
                  <button
                    key={col}
                    onClick={() => {
                      setSelectedColor(selectedColor === col ? "" : col);
                      setShowMobileFilters(false);
                    }}
                    className={`border text-[9px] font-bold px-3 py-1.5 uppercase ${
                      selectedColor === col
                        ? "bg-[#0a0a0a] border-black text-[#f8f7f2]"
                        : "border-[#1A1A1A]/10 bg-[#f8f7f2]/40"
                    }`}
                  >
                    {col}
                  </button>
                ))}
              </div>
            </div>

            {/* Price Slider */}
            <div className="space-y-3">
              <div className="flex justify-between items-center text-[10px] font-bold uppercase tracking-widest text-neutral-400">
                <span>Max Price</span>
                <span className="text-black font-sans text-xs">Rs. {priceRange.toLocaleString()}</span>
              </div>
              <input
                type="range"
                min="2000"
                max="15000"
                step="500"
                value={priceRange}
                onChange={(e) => setPriceRange(Number(e.target.value))}
                className="w-full h-1 bg-neutral-200 accent-[#0a0a0a] outline-none"
              />
            </div>

            <button
              onClick={handleClearFilters}
              className="bg-[#0A0A0A] text-white hover:bg-[#D4AF37] hover:text-black font-semibold text-xs tracking-widest py-3 text-center transition-all uppercase"
            >
              Clear All Filters
            </button>
          </div>
        </div>
      )}

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

export default function ShopPage() {
  return (
    <Suspense fallback={
      <div className="bg-[#F8F7F2] min-h-screen flex items-center justify-center text-xs font-bold uppercase tracking-widest text-neutral-400">
        Loading Starboy Archive...
      </div>
    }>
      <ShopContent />
    </Suspense>
  );
}
