'use client'
import { useState, useEffect } from 'react'
import { useMedusaCart } from '@/hooks/useMedusaCart'
import type { MedusaProduct } from '@/hooks/useMedusaProducts'
import Link from 'next/link'
import Image from 'next/image'
import { ShoppingBag, TrendingUp } 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 MostPopular() {
  const [products, setProducts] = useState<MedusaProduct[]>([])
  const [loading, setLoading] = useState(true)
  const { addToCart } = useMedusaCart()

  useEffect(() => {
    fetch('/api/popular-products?limit=8')
      .then(r => r.ok ? r.json() : Promise.reject(r.status))
      .then(d => { setProducts(d.products ?? []); setLoading(false) })
      .catch(() => {
        // fallback to latest products
        fetch('/api/medusa/products?limit=8')
          .then(r => r.json())
          .then(d => { setProducts(d.products ?? []); setLoading(false) })
          .catch(() => setLoading(false))
      })
  }, [])

  const featured = products.slice(0, 4)

  if (loading) return (
    <div className="py-12 flex justify-center">
      <div className="w-8 h-8 rounded-full border-2 border-primary border-t-transparent animate-spin" />
    </div>
  )
  if (featured.length === 0) return null

  return (
    <section className="py-10">
      <div className="flex items-center gap-2 mb-6">
        <TrendingUp className="h-5 w-5 text-primary" />
        <h2 className="text-xl font-bold text-foreground">Popular Picks</h2>
      </div>
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {featured.map((product, idx) => {
          const variant = product.variants?.[0]
          const price = variant?.prices?.[0]
          return (
            <div key={product.id} className="group bg-card rounded-xl overflow-hidden border border-border hover:shadow-md transition-all relative">
              {idx < 2 && (
                <span className="absolute top-2 left-2 z-10 bg-primary text-primary-foreground text-xs font-semibold px-2 py-0.5 rounded-full">
                  Best Seller
                </span>
              )}
              <Link href={`/products/${product.id}`} className="block overflow-hidden">
                <div className="relative aspect-square bg-muted">
                  {product.thumbnail ? (
                    <Image src={product.thumbnail} alt={product.title || ''} fill sizes="(max-width: 640px) 50vw, 25vw" className="object-cover group-hover:scale-105 transition-transform duration-300" />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center">
                      <ShoppingBag className="h-8 w-8 text-muted-foreground/30" />
                    </div>
                  )}
                </div>
              </Link>
              <div className="p-3">
                <Link href={`/products/${product.id}`}>
                  <p className="text-sm font-medium text-foreground line-clamp-2 mb-1 hover:text-primary transition-colors">{product.title}</p>
                </Link>
                {price && (
                  <p className="text-sm font-bold text-primary mb-2">
                    {formatPrice(price.amount, price.currency_code)}
                  </p>
                )}
                <button
                  onClick={() => { if (!variant?.id) return; addToCart(variant.id, 1); window.dispatchEvent(new CustomEvent('cart-drawer-open')) }}
                  disabled={!variant?.id}
                  className="w-full text-xs bg-primary/10 text-primary hover:bg-primary hover:text-primary-foreground py-1.5 rounded-lg transition-colors font-medium disabled:opacity-40"
                >
                  Add to Cart
                </button>
              </div>
            </div>
          )
        })}
      </div>
    </section>
  )
}
