'use client'

import { useRef, useState } from 'react'
import * as motion from 'framer-motion/m'
import { AnimatePresence } from 'framer-motion'
import Image from 'next/image'
import Link from 'next/link'
import { useTranslations, useLocale } from 'next-intl'
import { ShoppingCart, Check, Eye, SlidersHorizontal } from 'lucide-react'
import { useCartStore } from '@/store/cartStore'
import { useCartUI } from '@/components/frontend/cart/CartUIContext'
import { useCurrencyStore } from '@/store/currencyStore'
import { useQuickViewStore } from '@/store/quickViewStore'
import Button from './Button'
import WishlistButton from './WishlistButton'

interface ProductCardProps {
  id: string
  title: string
  price: number
  oldPrice?: number
  rating?: number
  reviews?: number
  image: string
  discount?: number
  variantId?: string | null
  // Only real DB-backed products have a slug — still-mock sections
  // (WeeklyOffers, ProductGrid, offers/OfferSection) don't pass one, so the
  // card renders without a link rather than pointing at a fake product page,
  // and without the Quick View affordance (it needs a real slug to fetch).
  slug?: string
  // 'variable' products can't be added to the cart directly from the card —
  // there's no variant selector here — so the primary CTA opens Quick View
  // instead of calling addToCart. Undefined (still-mock callers) behaves
  // like 'simple', i.e. today's unchanged Add to Cart button.
  productType?: 'simple' | 'variable'
  // First row(s) of a listing are usually the LCP element — load their image
  // eagerly with high fetch priority instead of the lazy default.
  priority?: boolean
  onAddToCart?: (e: React.MouseEvent) => void
}

export default function ProductCard({
  id,
  title,
  price,
  oldPrice,
  rating = 4,
  reviews = 0,
  image,
  discount,
  variantId = null,
  slug,
  productType = 'simple',
  priority = false,
  onAddToCart,
}: ProductCardProps) {
  const [added, setAdded] = useState(false)
  const [isFlying, setIsFlying] = useState(false)
  const [justPicked, setJustPicked] = useState(false)
  const imageWrapperRef = useRef<HTMLDivElement>(null)
  const { addToCart, loading } = useCartStore()
  const { fly } = useCartUI()
  const formatAmount = useCurrencyStore((s) => s.formatAmount)
  const openQuickView = useQuickViewStore((s) => s.open)
  const t = useTranslations('ProductCard')
  const tCart = useTranslations('Cart')
  const locale = useLocale()
  const isVariable = productType === 'variable'

  const handleQuickView = (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    if (slug) openQuickView(slug)
  }

  const discountPercent = discount || (oldPrice ? Math.round(((oldPrice - price) / oldPrice) * 100) : 0)
  // `image` is an emoji for the still-mock sections (WeeklyOffers,
  // CategoryProducts, ProductGrid, RelatedProducts) and a real image URL
  // for real DB-backed data (FlashSale) — render accordingly.
  const isImageUrl = image.startsWith('http')

  const handleAddToCart = async (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()

    if (isFlying) return // guard against double-fires while a throw is in flight

    // Call external handler if provided
    onAddToCart?.(e)

    // Picked-up pulse on the source image (~300ms) — set directly in the
    // handler, not an effect, so there's no set-state-in-effect risk.
    setJustPicked(true)
    setTimeout(() => setJustPicked(false), 300)

    if (isImageUrl && imageWrapperRef.current) {
      setIsFlying(true)
      fly(imageWrapperRef.current, image, () => setIsFlying(false))
    }

    // Add to cart via store (independent of the throw animation's timing —
    // the header badge bumps on its own once the store's items update)
    await addToCart(id, variantId, 1, {
      success: tCart('addedToCart'),
      failed: tCart('addToCartFailed'),
      networkError: tCart('networkError'),
    }, locale)

    // Show success state
    setAdded(true)
    setTimeout(() => setAdded(false), 1500)
  }

  return (
    <motion.div
      initial={{ opacity: 0, y: 30 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true }}
      whileHover={{ y: -8 }}
      transition={{ duration: 0.3 }}
      className="bg-white rounded-2xl overflow-hidden shadow-sm hover:shadow-xl transition-all duration-300"
    >
      <div className="bg-linear-to-br from-gray-50 to-white p-8 text-center relative">
        {isImageUrl ? (
          <motion.div
            ref={imageWrapperRef}
            className="relative w-full h-32"
            animate={justPicked ? { scale: 0.92, opacity: 0.7 } : { scale: 1, opacity: 1 }}
            transition={{ duration: 0.15 }}
          >
            {slug ? (
              <Link href={`/product/${slug}`} className="block relative w-full h-full">
                <Image src={image} alt={title} fill className="object-contain" sizes="(max-width: 768px) 50vw, 25vw" priority={priority} />
              </Link>
            ) : (
              <Image src={image} alt={title} fill className="object-contain" sizes="(max-width: 768px) 50vw, 25vw" priority={priority} />
            )}
          </motion.div>
        ) : (
          <span className="text-6xl">{image}</span>
        )}
        {slug && (
          <WishlistButton productId={id} variantId={variantId} size={16} className="absolute top-3 left-3 shadow-sm" />
        )}
        {discountPercent > 0 && (
          <span className="absolute top-3 right-3 bg-red-100 text-red-600 text-xs font-bold px-2 py-1 rounded-full">
            -{discountPercent}%
          </span>
        )}
      </div>
      <div className="p-5">
        {slug ? (
          <Link href={`/product/${slug}`}>
            <h3 className="font-semibold text-lg mb-1 hover:text-primary transition-colors">{title}</h3>
          </Link>
        ) : (
          <h3 className="font-semibold text-lg mb-1">{title}</h3>
        )}
        {rating > 0 && (
          <div className="flex items-center gap-1 mb-3">
            <div className="flex text-yellow-400">
              {'★'.repeat(Math.floor(rating))}
              {rating % 1 !== 0 && '½'}
              {'☆'.repeat(5 - Math.ceil(rating))}
            </div>
            <span className="text-xs text-gray-400">({reviews})</span>
          </div>
        )}
        <div className="flex items-center gap-2 mb-4">
          <span className="text-xl font-bold text-primary">{formatAmount(price)}</span>
          {oldPrice && (
            <span className="text-sm text-gray-400 line-through">{formatAmount(oldPrice)}</span>
          )}
        </div>
        {slug ? (
          <div className="flex gap-2">
            <button
              type="button"
              onClick={handleQuickView}
              aria-label={t('quickView')}
              title={t('quickView')}
              className="shrink-0 w-11 h-11 flex items-center justify-center rounded-lg border border-gray-200 text-dark hover:border-primary hover:text-primary transition-colors cursor-pointer"
            >
              <Eye size={18} />
            </button>

            {isVariable ? (
              <button
                type="button"
                onClick={handleQuickView}
                className="flex-1 flex items-center justify-center gap-2 rounded-lg font-semibold text-sm bg-secondary text-white hover:bg-secondary-dark transition-colors cursor-pointer"
              >
                <SlidersHorizontal size={16} />
                {t('selectOptions')}
              </button>
            ) : (
              <Button
                variant={added ? 'primary' : 'secondary'}
                onClick={handleAddToCart}
                disabled={loading || isFlying}
                className="flex-1 cursor-pointer overflow-hidden"
              >
                <AddToCartLabel added={added} busy={loading || isFlying} t={t} />
              </Button>
            )}
          </div>
        ) : (
          <Button
            variant={added ? 'primary' : 'secondary'}
            onClick={handleAddToCart}
            disabled={loading || isFlying}
            className="w-full cursor-pointer overflow-hidden"
          >
            <AddToCartLabel added={added} busy={loading || isFlying} t={t} />
          </Button>
        )}
      </div>
    </motion.div>
  )
}

function AddToCartLabel({
  added,
  busy,
  t,
}: {
  added: boolean
  busy: boolean
  t: ReturnType<typeof useTranslations>
}) {
  return (
    <AnimatePresence mode="wait" initial={false}>
      {added ? (
        <motion.span
          key="added"
          initial={{ y: 12, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          exit={{ y: -12, opacity: 0 }}
          transition={{ duration: 0.18 }}
          className="flex items-center justify-center gap-2"
        >
          <Check size={16} />
          {t('added')}
        </motion.span>
      ) : busy ? (
        <motion.span
          key="loading"
          initial={{ y: 12, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          exit={{ y: -12, opacity: 0 }}
          transition={{ duration: 0.18 }}
          className="flex items-center justify-center gap-2"
        >
          <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none"/>
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/>
          </svg>
          {t('adding')}
        </motion.span>
      ) : (
        <motion.span
          key="idle"
          initial={{ y: 12, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          exit={{ y: -12, opacity: 0 }}
          transition={{ duration: 0.18 }}
          className="flex items-center justify-center gap-2"
        >
          <ShoppingCart size={16} />
          {t('addToCart')}
        </motion.span>
      )}
    </AnimatePresence>
  )
}
