'use client'

import Image from 'next/image'
import { Package, Truck, Tag, ImageOff } from 'lucide-react'
import { useTranslations } from 'next-intl'
import { useCurrencyStore } from '@/store/currencyStore'
import type { CartItem, AppliedCoupon } from '@/store/cartStore'
import { computeItemCouponDiscounts } from '@/lib/cart/itemCouponDiscount'

interface OrderSummaryProps {
  items: CartItem[]
  subtotal: number
  deliveryFee: number
  tax?: number
  vatLabel?: string
  vatPercentage?: number
  discount: number
  total: number
  appliedCoupon?: AppliedCoupon | null
}

// Reuses the Cart namespace's own subtotal/deliveryFee/discount/total labels
// — this is the same order-summary sidebar shown on /cart, just with the
// payment-method step ahead of it instead of behind, so duplicating a
// second translated copy of the same four words isn't worth it.
export default function OrderSummary({ items, subtotal, deliveryFee, tax = 0, vatLabel = 'GST', vatPercentage = 0, discount, total, appliedCoupon }: OrderSummaryProps) {
  const t = useTranslations('Cart')
  const formatAmount = useCurrencyStore((s) => s.formatAmount)
  const showEligibilityTags = Boolean(appliedCoupon && !appliedCoupon.appliesToAll)
  const itemDiscounts = computeItemCouponDiscounts(items, discount)

  return (
    <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 sticky top-24">
      <h3 className="font-semibold text-dark mb-4 flex items-center gap-2">
        <Package size={18} className="text-primary" />
        {t('orderSummary')}
      </h3>

      <div className="space-y-3 max-h-60 overflow-y-auto mb-4">
        {items.map((item) => (
          <div key={item.id} className="flex items-center gap-3 text-sm">
            <div className="relative w-10 h-10 shrink-0 rounded-lg overflow-hidden bg-light-gray">
              {item.image_url ? (
                <Image src={item.image_url} alt={item.product_name} fill className="object-cover" sizes="40px" />
              ) : (
                <div className="w-full h-full flex items-center justify-center">
                  <ImageOff size={14} className="text-gray-300" />
                </div>
              )}
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-gray-custom truncate">
                {item.product_name} <span className="text-dark">x{item.quantity}</span>
              </p>
              {item.variant_name && <p className="text-xs text-gray-400 truncate">{item.variant_name}</p>}
              {showEligibilityTags && (
                <span
                  className={`inline-block mt-0.5 text-[10px] font-medium px-1.5 py-0.5 rounded-full ${
                    item.coupon_eligible ? 'text-green-700 bg-green-50' : 'text-gray-500 bg-gray-100'
                  }`}
                >
                  {item.coupon_eligible ? t('couponEligible') : t('couponNotEligible')}
                </span>
              )}
            </div>
            {(() => {
              const itemDiscount = itemDiscounts.get(item.id) ?? 0
              return itemDiscount > 0 ? (
                <div className="flex items-baseline gap-1.5 shrink-0">
                  <span className="text-[11px] text-gray-400 line-through">{formatAmount(Number(item.subtotal))}</span>
                  <span className="text-dark">{formatAmount(Number(item.subtotal) - itemDiscount)}</span>
                </div>
              ) : (
                <span className="text-dark shrink-0">{formatAmount(Number(item.subtotal))}</span>
              )
            })()}
          </div>
        ))}
      </div>

      <div className="border-t border-gray-100 pt-4 space-y-2">
        <div className="flex justify-between text-sm">
          <span className="text-gray-custom">{t('subtotal')}</span>
          <span className="text-dark">{formatAmount(subtotal)}</span>
        </div>
        <div className="flex justify-between text-sm">
          <span className="text-gray-custom flex items-center gap-1">
            <Truck size={14} /> {t('deliveryFee')}
          </span>
          <span className="text-dark">{deliveryFee === 0 ? t('free') : formatAmount(deliveryFee)}</span>
        </div>
        {tax > 0 && (
          <div className="flex justify-between text-sm">
            <span className="text-gray-custom">{vatLabel} ({vatPercentage}%)</span>
            <span className="text-dark">{formatAmount(tax)}</span>
          </div>
        )}
        {discount > 0 && (
          <div className="flex justify-between text-sm text-green-600">
            <span className="flex items-center gap-1">
              <Tag size={14} /> {t('discount')}
            </span>
            <span>- {formatAmount(discount)}</span>
          </div>
        )}
      </div>

      <div className="border-t border-gray-100 mt-4 pt-4">
        <div className="flex justify-between">
          <span className="font-semibold text-dark">{t('total')}</span>
          <span className="font-bold text-xl text-primary">{formatAmount(total)}</span>
        </div>
      </div>
    </div>
  )
}
