'use client'

import { useState } from 'react'
import Link from 'next/link'
import Image from 'next/image'
import { Minus, Plus, Trash2, ImageOff } from 'lucide-react'
import * as motion from 'framer-motion/m'
import { useTranslations } from 'next-intl'
import { useCurrencyStore } from '@/store/currencyStore'

interface CartItemProps {
  id: string
  name: string
  variantName?: string | null
  price: number
  quantity: number
  imageUrl: string | null
  slug: string | null
  inStock: boolean
  // null when no coupon is currently applied to the cart at all — the
  // eligible/not-eligible tag only renders once there's something to be
  // eligible (or not) for. See cartStore.ts's own CartItem.coupon_eligible.
  couponEligible?: boolean | null
  // This line's share of the cart's coupon discount (0 = none) — see
  // itemCouponDiscount.ts. Shown as a struck-through original total next
  // to the discounted one, in the single price spot this card has (no
  // separate unit-price line any more — see the removed line below).
  itemDiscount?: number
  onUpdateQuantity: (id: string, quantity: number) => void
  onRemove: (id: string) => void
}

export default function CartItem({
  id,
  name,
  variantName,
  price,
  quantity,
  imageUrl,
  slug,
  inStock,
  couponEligible = null,
  itemDiscount = 0,
  onUpdateQuantity,
  onRemove,
}: CartItemProps) {
  const [isLoading, setIsLoading] = useState(false)
  const formatAmount = useCurrencyStore((s) => s.formatAmount)
  const t = useTranslations('Cart')

  const handleQuantityChange = async (newQuantity: number) => {
    if (newQuantity < 1 || newQuantity > 99) return
    setIsLoading(true)
    await onUpdateQuantity(id, newQuantity)
    setIsLoading(false)
  }

  const image = (
    <div className="relative sm:w-24 h-24 w-full bg-gray-50 rounded-xl flex items-center justify-center shrink-0 overflow-hidden">
      {imageUrl ? (
        <Image src={imageUrl} alt={name} fill className="object-contain" sizes="96px" />
      ) : (
        <ImageOff size={28} className="text-gray-300" />
      )}
    </div>
  )

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, x: -100 }}
      className="flex flex-col sm:flex-row gap-4 py-6 border-b border-gray-100 last:border-0"
    >
      {/* Product Image */}
      {slug ? <Link href={`/product/${slug}`} className="shrink-0">{image}</Link> : image}

      {/* Product Details */}
      <div className="flex-1">
        <div className="flex flex-wrap justify-between gap-2">
          <div>
            {slug ? (
              <Link href={`/product/${slug}`}>
                <h3 className="font-semibold text-dark hover:text-primary transition">{name}</h3>
              </Link>
            ) : (
              <h3 className="font-semibold text-dark">{name}</h3>
            )}
            {variantName && <p className="text-xs text-gray-custom mt-0.5">{variantName}</p>}
            {couponEligible === true && (
              <span className="inline-block mt-1 text-[11px] font-medium text-green-700 bg-green-50 px-2 py-0.5 rounded-full">
                {t('couponEligible')}
              </span>
            )}
            {couponEligible === false && (
              <span className="inline-block mt-1 text-[11px] font-medium text-gray-500 bg-gray-100 px-2 py-0.5 rounded-full">
                {t('couponNotEligible')}
              </span>
            )}
          </div>

          <button
            onClick={() => onRemove(id)}
            className="text-gray-custom hover:text-red-500 transition p-1"
            disabled={isLoading}
          >
            <Trash2 size={18} />
          </button>
        </div>

        <div className="flex flex-wrap justify-between items-center mt-4">
          <div className="flex items-center border border-gray-200 rounded-lg">
            <button
              onClick={() => handleQuantityChange(quantity - 1)}
              disabled={quantity <= 1 || isLoading}
              className="p-2 px-3 rounded-l-lg hover:bg-gray-50 transition disabled:opacity-50"
            >
              <Minus size={14} />
            </button>
            <span className="w-10 text-center text-dark font-medium">{quantity}</span>
            <button
              onClick={() => handleQuantityChange(quantity + 1)}
              disabled={quantity >= 99 || isLoading}
              className="p-2 px-3 rounded-r-lg hover:bg-gray-50 transition disabled:opacity-50"
            >
              <Plus size={14} />
            </button>
          </div>

          <div className="text-right">
            <p className="text-sm text-gray-custom">{t('total')}</p>
            {itemDiscount > 0 ? (
              <div className="flex items-baseline gap-2 justify-end">
                <span className="text-xs text-gray-400 line-through">{formatAmount(price * quantity)}</span>
                <span className="font-bold text-dark">{formatAmount(price * quantity - itemDiscount)}</span>
              </div>
            ) : (
              <p className="font-bold text-dark">{formatAmount(price * quantity)}</p>
            )}
          </div>
        </div>

        {!inStock && (
          <p className="text-xs text-red-500 mt-2">{t('outOfStockRemove')}</p>
        )}
      </div>
    </motion.div>
  )
}
