import { useState, useEffect, useMemo, useCallback } from "react"
import { Link, useSearchParams } from "react-router"
import { useCart } from "@/context/CartContext"
import { Search, ShoppingCart, Star, Loader2 } from "lucide-react"
import { filterAndSortProducts, getCategories, getProductImage, type Product } from "@/data/staticData"
import { SEO } from "@/components/SEO"

const CAT_NAMES: Record<string, string> = { "design-tools": "Design Tools", "ai-tools": "AI Tools", "streaming": "Streaming", "productivity": "Productivity", "security": "Security & VPN", "developer": "Developer Tools", "microsoft": "Microsoft Office", "learning": "Learning", "combo-offers": "Combo Offers" }

export default function Shop() {
  const [searchParams, setSearchParams] = useSearchParams()
  const [search, setSearch] = useState("")
  const [category, setCategory] = useState(searchParams.get("category") || "")
  const [sort, setSort] = useState<string>("popular")
  const [addingId, setAddingId] = useState<string | null>(null)
  const { addItem } = useCart()

  const handleAdd = useCallback((productId: string) => {
    setAddingId(productId)
    addItem(productId)
    setTimeout(() => setAddingId(null), 600)
  }, [addItem])

  useEffect(() => { const cat = searchParams.get("category"); if (cat) setCategory(cat) }, [searchParams])

  const categories = useMemo(() => getCategories(), [])
  const products = useMemo(() => {
    return filterAndSortProducts({
      category: category || undefined,
      search: search || undefined,
      sort: sort === "popular" ? undefined : sort,
    })
  }, [category, search, sort])

  const handleCategory = (cat: string) => { setCategory(cat); cat ? setSearchParams({ category: cat }) : setSearchParams({}) }

  return (
    <>
      <SEO
        title={category ? `${CAT_NAMES[category] || category} | Shop Premium Subscriptions` : "Shop | 81+ Premium Subscriptions Up to 96% Off"}
        description={category ? `Buy cheap ${CAT_NAMES[category] || category} subscriptions. Save up to 96% on premium tools. Instant delivery, 24H money-back guarantee.` : "Shop 81+ premium subscriptions at up to 96% off. Netflix, Spotify, ChatGPT Plus, Canva Pro, Adobe Creative Cloud & more. Instant delivery."}
        keywords={`cheap ${category || 'premium'} subscriptions, buy ${category || 'software'} subscriptions, discount ${category || 'premium'} tools, ${category || 'software'} deals`}
        path={`/shop${category ? `?category=${category}` : ''}`}
      />
      <div className="min-h-screen pt-28 pb-16 px-4">
        <div className="max-w-7xl mx-auto">
          <div className="mb-8"><h1 className="text-4xl font-bold mb-2">{category ? CAT_NAMES[category] || category : "All Products"}</h1><p className="text-slate-400">{products?.length || 0} premium subscriptions available</p></div>
          <div className="flex flex-col md:flex-row gap-4 mb-8">
            <div className="flex-1 relative"><Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-500" /><input type="text" placeholder="Search products..." value={search} onChange={e => setSearch(e.target.value)} className="w-full pl-12 pr-4 py-3 rounded-xl bg-white/5 border border-white/10 text-white placeholder:text-slate-500 focus:outline-none focus:border-[#f97316] transition-colors" /></div>
            <select value={sort} onChange={e => setSort(e.target.value)} className="px-4 py-3 rounded-xl bg-white/5 border border-white/10 text-white focus:outline-none focus:border-[#f97316]">
              <option value="popular">Most Popular</option><option value="price-asc">Price: Low to High</option><option value="price-desc">Price: High to Low</option><option value="newest">Newest</option>
            </select>
          </div>
          <div className="flex flex-wrap gap-2 mb-8">
            <button onClick={() => handleCategory("")} className={`px-4 py-2 rounded-full text-sm transition-all ${!category ? "bg-[#f97316] text-white" : "bg-white/5 border border-white/10 hover:bg-white/10"}`}>All</button>
            {categories.map(cat => (<button key={cat.id} onClick={() => handleCategory(cat.id)} className={`px-4 py-2 rounded-full text-sm transition-all ${category === cat.id ? "bg-[#f97316] text-white" : "bg-white/5 border border-white/10 hover:bg-white/10"}`}>{cat.name} <span className="opacity-60">({cat.productCount})</span></button>))}
          </div>
          {products.length === 0 ? <div className="text-center py-20"><p className="text-slate-400 text-lg">No products found</p><button onClick={() => { setSearch(""); setCategory("") }} className="mt-4 btn-primary text-sm">Clear Filters</button></div> :
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
              {products.map((p: Product) => { const discount = Math.round(((p.originalPrice - p.price) / p.originalPrice) * 100); const img = getProductImage(p.slug, p.category)
                return (<div key={p.id} className="group glass-card overflow-hidden hover:border-[#f97316]/30 transition-all duration-300">
                  <Link to={`/product/${p.slug}`} className="block relative h-48 overflow-hidden"><img src={img} alt={p.name} className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500" loading="lazy" /><div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent" />{p.badge && <div className="absolute top-3 left-3 px-3 py-1 rounded-full bg-[#f97316] text-xs font-bold">{p.badge}</div>}<div className="absolute top-3 right-3 px-2 py-1 rounded-full bg-red-500/80 text-xs font-bold">{discount}% OFF</div></Link>
                  <div className="p-4"><div className="flex items-center gap-1 mb-1">{[1,2,3,4,5].map(s => <Star key={s} className="w-3 h-3 fill-[#f97316] text-[#f97316]" />)}<span className="text-xs text-slate-400 ml-1">5.0</span></div>
                    <Link to={`/product/${p.slug}`}><h3 className="font-semibold mb-1 group-hover:text-[#f97316] transition-colors line-clamp-1">{p.name}</h3></Link>
                    <p className="text-xs text-slate-400 mb-3 line-clamp-2">{p.shortDescription}</p>
                    <div className="flex items-center justify-between"><div><span className="text-lg font-bold text-[#f97316]">${p.price}</span><span className="text-xs text-slate-500 line-through ml-2">${p.originalPrice}</span></div>
                      <div className="flex gap-1"><button
                        onClick={e => { e.preventDefault(); handleAdd(p.id) }}
                        disabled={addingId === p.id}
                        className="p-2 rounded-full bg-[#f97316]/10 hover:bg-[#f97316] hover:text-white transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                        aria-label="Add to cart"
                      >
                        {addingId === p.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <ShoppingCart className="w-4 h-4" />}
                      </button></div>
                    </div>
                    <div className="mt-2 flex items-center justify-between"><div className="flex items-center gap-1 text-xs text-green-400"><span>✓</span><span>Instant Delivery</span></div><span className="text-xs text-slate-500">{p.deliveryTime}</span></div>
                  </div>
                </div>)
              })}
            </div>}
        </div>
      </div>
    </>
  )
}
