'use client'

import { useState, useCallback } from "react"
import Image from "next/image"
import Link from "next/link"
import Button from "@/components/ui/Button"
import { Plus, ShoppingBag } from 'lucide-react'
import { useMedusaProducts } from "@/hooks/useMedusaProducts"
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)}`
}

function ProductCard({ product }: { product: any }) {
  const { addToCart } = useMedusaCart()
  const [adding, setAdding] = useState(false)

  const handleAddToCart = useCallback(
    async (e: React.MouseEvent) => {
      e.preventDefault()
      e.stopPropagation()
      const variant = product.variants?.[0]
      if (!variant) return
      setAdding(true)
      try {
        await addToCart(variant.id, 1)
        window.dispatchEvent(new CustomEvent("cart-drawer-open"))
      } catch {
        console.error("Failed to add to cart")
      } finally {
        setAdding(false)
      }
    },
    [product, addToCart]
  )

  const price = product.variants?.[0]?.prices?.[0]

  return (
    <Link data-vula-section="featuredproducts"
      href={`/products/${product.id}`}
      className="group block rounded-none overflow-hidden bg-white border border-neutral-100 hover:shadow-[var(--shadow-lifted)] hover:-translate-y-0.5 transition-all duration-200 ease-out"
    >
      <div className="relative aspect-[4/5] overflow-hidden bg-neutral-100">
        {product.thumbnail ? (
          <Image
            src={product.thumbnail}
            alt={product.title}
            fill
            sizes="(max-width: 768px) 50vw, 25vw"
            className="object-cover group-hover:scale-105 transition-transform duration-500 ease-out"
          />
        ) : (
          <div className="flex items-center justify-center h-full text-neutral-300">
            <ShoppingBag className="w-12 h-12" />
          </div>
        )}
        <button
          onClick={handleAddToCart}
          disabled={adding}
          className="absolute bottom-3 right-3 bg-[#ea580c] text-white p-3 rounded-full shadow-lg hover:bg-[#ea580c]/90 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
          aria-label={`Add ${product.title} to cart`}
        >
          <Plus className="w-5 h-5" />
        </button>
      </div>
      <div className="p-4 space-y-2">
        <h3 className="text-sm font-medium tracking-wide text-[#0a0a0a] truncate">
          {product.title}
        </h3>
        {price && (
          <p className="text-base font-semibold text-[#ea580c]">
            {formatPrice(price.amount, price.currency_code)}
          </p>
        )}
      </div>
    </Link>
  )
}

export default function FeaturedProducts() {
  const { products, isLoading } = useMedusaProducts(8)

  if (isLoading) {
    return (
      <section className="py-20 lg:py-28 bg-white" id="products">
        <div className="container mx-auto px-6 max-w-6xl">
          <h2 className="text-3xl lg:text-4xl font-semibold tracking-tight text-[#0a0a0a] mb-12">
            Featured Drops
          </h2>
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
            {Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="animate-pulse aspect-[4/5] bg-neutral-100 rounded-none" />
            ))}
          </div>
        </div>
      </section>
    )
  }

  return (
    <section className="py-20 lg:py-28 bg-white" id="products">
      <div className="container mx-auto px-6 max-w-6xl">
        <div className="flex items-center justify-between mb-12">
          <h2 className="text-3xl lg:text-4xl font-semibold tracking-tight text-[#0a0a0a]">
            Featured Drops
          </h2>
          <Link href="/products">
            <Button variant="ghost" className="text-[#ea580c] font-medium underline-offset-4 hover:underline">
              View All
            </Button>
          </Link>
        </div>
        {products && products.length > 0 ? (
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
            {products.slice(0, 8).map((product) => (
              <ProductCard key={product.id} product={product} />
            ))}
          </div>
        ) : (
          <div className="text-center py-20 text-neutral-400">
            <ShoppingBag className="w-16 h-16 mx-auto mb-4" />
            <p className="text-lg">No products available yet. Check back soon.</p>
          </div>
        )}
      </div>
    </section>
  )
}
