'use client'
import { useEffect, useState } from 'react'
import Link from 'next/link'
import Image from 'next/image'
import { ShoppingBag } from 'lucide-react'
import { useMedusaCart } from '@/hooks/useMedusaCart'

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)}`
}

interface Variant { id: string; prices: Array<{ amount: number; currency_code: string }> }
interface Product { id: string; title: string; thumbnail: string | null; variants: Variant[]; collection?: { id: string } }

export default function YouMayAlsoLike({ currentProductId, collectionId }: { currentProductId: string; collectionId?: string }) {
  const [products, setProducts] = useState<Product[]>([])
  const { addToCart } = useMedusaCart()

  useEffect(() => {
    const params = new URLSearchParams({ limit: '8' })
    if (collectionId) params.set('collection_id[]', collectionId)
    fetch(`/api/medusa/store/products?${params}`)
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        if (!data?.products) return
        setProducts(data.products.filter((p: Product) => p.id !== currentProductId).slice(0, 4))
      })
      .catch(() => {})
  }, [currentProductId, collectionId])

  if (products.length === 0) return null

  return (
    <section className="mt-20 pt-12 border-t border-border">
      <h2 className="text-2xl font-bold text-foreground mb-8">You May Also Like</h2>
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {products.map(product => {
          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">
              <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>
  )
}
