'use client'

import { useMedusaProducts, MedusaProduct } from '@/hooks/useMedusaProducts'
import { useMedusaCart } from '@/hooks/useMedusaCart'
import Button from '@/components/ui/Button'
import Badge from '@/components/ui/Badge'
import { Card, CardContent } from '@/components/ui/Card'
import Image from 'next/image'
import Link from 'next/link'
import { Eye, ShoppingBag } 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)}`
}

function ProductCard({ product }: { product: MedusaProduct }) {
  const { addToCart } = useMedusaCart()
  const variant = product.variants?.[0]
  const price = variant?.prices?.[0]
  const isLimited = Math.random() > 0.7

  const handleAddToCart = () => {
    if (!variant) return
    addToCart(variant.id, 1)
    window.dispatchEvent(new CustomEvent('cart-drawer-open'))
  }

  return (
    <Card className="relative border-[3px] border-[#18181b] shadow-[4px_4px_0_0_#dc2626] group">
      <Link href={`/products/${product.id}`} className="block">
        <div className="relative aspect-square overflow-hidden">
          {product.thumbnail ? (
            <Image
              src={product.thumbnail}
              alt={product.title}
              fill
              sizes="(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 25vw"
              className="object-cover transition-transform duration-500 ease-out group-hover:scale-105"
            />
          ) : (
            <div className="h-full w-full bg-gray-100 flex items-center justify-center">
              <ShoppingBag className="w-12 h-12 text-gray-400" />
            </div>
          )}
          <div className="absolute inset-0 bg-[#18181b]/0 group-hover:bg-[#18181b]/30 transition-all duration-200 ease-out flex items-center justify-center opacity-0 group-hover:opacity-100">
            <Eye className="w-8 h-8 text-white" />
          </div>
          {isLimited && (
            <Badge
              variant="accent"
              className="absolute top-2 left-2 uppercase text-xs font-bold bg-[#dc2626] text-white border-0"
            >
              Limited stock
            </Badge>
          )}
        </div>
      </Link>
      <CardContent className="p-4">
        <h3 className="font-bold uppercase text-sm text-[#18181b] truncate">
          {product.title}
        </h3>
        {price && (
          <p className="text-[#dc2626] font-black text-lg mt-1">
            {formatPrice(price.amount, price.currency_code)}
          </p>
        )}
        <Button
          variant="default"
          size="sm"
          className="w-full mt-3 uppercase bg-[#d4af37] hover:bg-[#b8962e] text-[#18181b] font-bold"
          onClick={handleAddToCart}
        >
          Bamba i-drop
        </Button>
      </CardContent>
    </Card>
  )
}

export default function FreshKasiDropsSection() {
  const { products, isLoading } = useMedusaProducts(12)
  if (isLoading) {
    return (
      <div className="flex justify-center py-16">
        <div className="w-8 h-8 rounded-full border-2 border-current border-t-transparent animate-spin" />
      </div>
    )
  }
  if (products.length === 0) return null

  return (
    <section
      id="fresh-kasi-drops"
      data-vula-section="fresh-kasi-drops"
      className="bg-[#ffffff] py-16 px-4"
    >
      <div className="max-w-6xl mx-auto">
        <div className="mb-10 border-b-[3px] border-[#d4af37] pb-4">
          <span className="bg-[#dc2626] text-white font-black uppercase text-sm px-4 py-1 inline-block mb-2">
            Fresh off the press
          </span>
          <h2 className="text-4xl font-black uppercase tracking-tighter text-[#18181b]">
            Fresh Kasi Drops
          </h2>
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
          {products.map((product) => (
            <ProductCard key={product.id} product={product} />
          ))}
        </div>
      </div>
    </section>
  )
}
