'use client'
import { useState, useMemo } from 'react'
import { useProducts } from '@/hooks/useProducts'
import { useVulaCart } from '@/hooks/useVulaCart'
import ProductFilters, { FilterState } from '@/components/shop/ProductFilters'
import ProductSort, { SortOption } from '@/components/shop/ProductSort'
import Image from 'next/image'
import Link from 'next/link'
import { Search, ShoppingBag, ShoppingCart, SlidersHorizontal, X } from 'lucide-react'

const CURRENCY_SYMBOLS: Record<string, string> = { zar: 'R', usd: '$', eur: '€', gbp: '£', kes: 'KSh', ngn: '₦', ghs: '₵' }
const formatPrice = (amount: number, code?: string) => {
  const sym = CURRENCY_SYMBOLS[(code ?? '').toLowerCase()] ?? (code?.toUpperCase() ?? '')
  return `${sym}${(amount / 100).toFixed(2)}`
}

export default function ProductsPage() {
  const { products, loading, error } = useProducts(100)
  const { addToCart } = useVulaCart()
  const [sort, setSort] = useState<SortOption>('featured')
  const [filters, setFilters] = useState<FilterState>({ category: '', maxPrice: 0, inStockOnly: false })
  const [search, setSearch] = useState('')
  const [filtersOpen, setFiltersOpen] = useState(false)

  const categories = useMemo(() => {
    const seen = new Map<string, string>()
    products.forEach(p => {
      if ((p as any).categories?.length) {
        (p as any).categories.forEach((cat: { id: string; name: string }) => seen.set(cat.id, cat.name))
      } else if ((p as any).collection?.id) {
        seen.set((p as any).collection.id, (p as any).collection.title ?? (p as any).collection.id)
      }
    })
    return Array.from(seen.entries()).map(([id, title]) => ({ id, title }))
  }, [products])

  const displayed = useMemo(() => {
    let list = [...products]
    if (search.trim()) {
      const q = search.toLowerCase()
      list = list.filter(p => p.title?.toLowerCase().includes(q) || p.description?.toLowerCase().includes(q))
    }
    if (filters.category) list = list.filter(p =>
      (p as any).categories?.some((c: { id: string }) => c.id === filters.category) || (p as any).collection?.id === filters.category
    )
    if (filters.maxPrice > 0) list = list.filter(p => {
      const price = p.variants?.[0]?.prices?.[0]?.amount ?? 0
      return price > 0 && price / 100 <= filters.maxPrice
    })
    if (filters.inStockOnly) list = list.filter(p => (p.variants?.length ?? 0) > 0)
    switch (sort) {
      case 'price-asc':  list.sort((a, b) => (a.variants?.[0]?.prices?.[0]?.amount ?? 0) - (b.variants?.[0]?.prices?.[0]?.amount ?? 0)); break
      case 'price-desc': list.sort((a, b) => (b.variants?.[0]?.prices?.[0]?.amount ?? 0) - (a.variants?.[0]?.prices?.[0]?.amount ?? 0)); break
      case 'newest':     list.sort((a, b) => new Date(b.created_at ?? 0).getTime() - new Date(a.created_at ?? 0).getTime()); break
      case 'name-asc':   list.sort((a, b) => (a.title ?? '').localeCompare(b.title ?? '')); break
    }
    return list
  }, [products, filters, sort, search])

  const resetFilters = () => setFilters({ category: '', maxPrice: 0, inStockOnly: false })

  if (loading) return (
    <div className="min-h-screen flex items-center justify-center bg-background">
      <div className="text-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4" />
        <p className="text-muted-foreground">Loading products...</p>
      </div>
    </div>
  )

  if (error) return (
    <div className="min-h-screen flex items-center justify-center bg-background">
      <p className="text-destructive">Failed to load products. Please try again.</p>
    </div>
  )

  return (
    <main className="min-h-screen bg-background">
      <div className="container mx-auto px-4 py-10">
        {/* Header */}
        <div className="flex items-center justify-between mb-8">
          <h1 className="text-3xl font-bold text-foreground">Products</h1>
          <button onClick={() => window.dispatchEvent(new CustomEvent('cart-drawer-open'))} className="flex items-center gap-2 text-muted-foreground hover:text-foreground transition-colors">
            <ShoppingCart className="h-5 w-5" />
            <span className="text-sm font-medium">Cart</span>
          </button>
        </div>

        {/* Search */}
        <div className="relative mb-6">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <input
            type="text"
            placeholder="Search products..."
            value={search}
            onChange={e => setSearch(e.target.value)}
            className="w-full pl-10 pr-4 py-2.5 bg-background border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
          />
          {search && (
            <button onClick={() => setSearch('')} className="absolute right-3 top-1/2 -translate-y-1/2">
              <X className="h-4 w-4 text-muted-foreground hover:text-foreground" />
            </button>
          )}
        </div>

        <div className="flex gap-8">
          {/* Sidebar filters — desktop */}
          {categories.length > 0 && (
            <aside className="hidden lg:block w-56 shrink-0">
              <ProductFilters
                categories={categories}
                filters={filters}
                onChange={setFilters}
                onReset={resetFilters}
              />
            </aside>
          )}

          {/* Mobile filter toggle */}
          <div className="flex-1 min-w-0">
            {categories.length > 0 && (
              <button
                onClick={() => setFiltersOpen(true)}
                className="lg:hidden flex items-center gap-2 text-sm border border-border px-4 py-2 rounded-lg mb-4 hover:bg-muted transition-colors"
              >
                <SlidersHorizontal className="h-4 w-4" />
                Filters
              </button>
            )}

            {/* Sort bar */}
            <div className="mb-6">
              <ProductSort value={sort} onChange={setSort} count={displayed.length} />
            </div>

            {/* Grid */}
            {displayed.length === 0 ? (
              <div className="text-center py-20">
                <ShoppingBag className="h-16 w-16 mx-auto mb-4 text-muted-foreground/40" />
                <p className="text-muted-foreground text-lg mb-2">No products found.</p>
                <button onClick={() => { resetFilters(); setSearch('') }} className="text-primary text-sm hover:underline">
                  Clear filters
                </button>
              </div>
            ) : (
              <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-5">
                {displayed.map((product) => {
                  const variant = product.variants?.[0]
                  const price = variant?.prices?.[0]
                  const imageUrl = product.thumbnail || (product as any).images?.[0]?.url
                  return (
                    <div key={product.id} className="bg-card rounded-xl overflow-hidden border border-border hover:shadow-lg transition-all duration-300 flex flex-col group">
                      <Link href={`/products/${product.id}`} className="block overflow-hidden">
                        {imageUrl ? (
                          <div className="relative aspect-square overflow-hidden bg-muted">
                            <Image src={imageUrl} alt={product.title || 'Product'} fill sizes="(max-width: 640px) 100vw, (max-width: 1280px) 50vw, 33vw" className="object-cover group-hover:scale-105 transition-transform duration-500" />
                          </div>
                        ) : (
                          <div className="aspect-square bg-muted flex items-center justify-center">
                            <ShoppingBag className="h-12 w-12 text-muted-foreground/30" />
                          </div>
                        )}
                      </Link>
                      <div className="p-4 flex flex-col flex-1">
                        <Link href={`/products/${product.id}`}>
                          <h2 className="font-semibold text-foreground mb-1 line-clamp-2 hover:text-primary transition-colors">{product.title}</h2>
                        </Link>
                        {product.collection?.title && (
                          <span className="text-xs text-muted-foreground mb-2">{product.collection.title}</span>
                        )}
                        {product.description && (
                          <p className="text-sm text-muted-foreground mb-3 line-clamp-2 flex-1">{product.description}</p>
                        )}
                        {price && (
                          <p className="text-lg font-bold text-primary mb-3">
                            {formatPrice(price.amount, price.currency_code)}
                          </p>
                        )}
                        <button
                          onClick={() => { if (!variant?.id) return; addToCart({ variantId: variant.id, productId: product.id, title: product.title, variant_title: variant.title ?? '', unit_price: variant.prices?.[0]?.amount ?? 0, quantity: 1, thumbnail: product.thumbnail ?? null }); window.dispatchEvent(new CustomEvent('cart-drawer-open')) }}
                          disabled={!variant?.id}
                          className="w-full bg-primary text-primary-foreground py-2 px-4 rounded-lg hover:bg-primary/90 transition-colors text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                          Add to Cart
                        </button>
                      </div>
                    </div>
                  )
                })}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Mobile filter drawer */}
      {filtersOpen && (
        <div className="fixed inset-0 z-50 lg:hidden">
          <div className="absolute inset-0 bg-black/50" onClick={() => setFiltersOpen(false)} />
          <div className="absolute right-0 top-0 h-full w-72 bg-background p-6 overflow-y-auto">
            <ProductFilters
              categories={categories}
              filters={filters}
              onChange={setFilters}
              onReset={resetFilters}
              isMobile
              onClose={() => setFiltersOpen(false)}
            />
          </div>
        </div>
      )}
    </main>
  )
}
