'use client'

import { useState } from 'react'
import * as motion from 'framer-motion/m'
import { Shield, Truck, CreditCard, Gift, Tag, Lock, X } from 'lucide-react'
import { useTranslations } from 'next-intl'
import { useCurrencyStore } from '@/store/currencyStore'
import { useCheckoutSettingsStore } from '@/store/checkoutSettingsStore'
import type { AppliedCoupon } from '@/store/cartStore'

interface CartSummaryProps {
  subtotal: number
  deliveryFee: number
  tax?: number
  vatLabel?: string
  vatPercentage?: number
  discount: number
  total: number
  appliedCouponCode?: string | null
  appliedCoupon?: AppliedCoupon | null
  onApplyCoupon?: (code: string) => Promise<void> | void
  onRemoveCoupon?: () => Promise<void> | void
  onProceedToCheckout: () => void
  isCheckoutDisabled?: boolean
  blockedReason?: string
}

export default function CartSummary({
  subtotal,
  deliveryFee,
  tax = 0,
  vatLabel = 'GST',
  vatPercentage = 0,
  discount,
  total,
  appliedCouponCode,
  appliedCoupon,
  onApplyCoupon,
  onRemoveCoupon,
  onProceedToCheckout,
  isCheckoutDisabled = false,
  blockedReason,
}: CartSummaryProps) {
  const formatAmount = useCurrencyStore((s) => s.formatAmount)
  const freeDeliveryThreshold = useCheckoutSettingsStore((s) => s.freeDeliveryThreshold)
  const t = useTranslations('Cart')
  const [couponCode, setCouponCode] = useState('')
  const [couponError, setCouponError] = useState('')
  const [isApplying, setIsApplying] = useState(false)

  const handleApplyCoupon = async () => {
    if (!couponCode.trim()) {
      setCouponError(t('couponRequired'))
      return
    }
    setCouponError('')
    setIsApplying(true)
    await onApplyCoupon?.(couponCode.trim())
    setIsApplying(false)
    setCouponCode('')
  }

  return (
    <motion.div
      initial={{ opacity: 0, x: 20 }}
      animate={{ opacity: 1, x: 0 }}
      className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 sticky top-24"
    >
      <h3 className="text-lg font-semibold text-dark mb-4">{t('orderSummary')}</h3>

      {/* Price Breakdown */}
      <div className="space-y-3 pb-4 border-b border-gray-100">
        <div className="flex justify-between">
          <span className="text-gray-custom">{t('subtotal')}</span>
          <span className="text-dark">{formatAmount(subtotal)}</span>
        </div>
        <div className="flex justify-between">
          <span className="text-gray-custom">{t('deliveryFee')}</span>
          <span className="text-dark">{deliveryFee === 0 ? t('free') : formatAmount(deliveryFee)}</span>
        </div>
        {tax > 0 && (
          <div className="flex justify-between">
            <span className="text-gray-custom">{vatLabel} ({vatPercentage}%)</span>
            <span className="text-dark">{formatAmount(tax)}</span>
          </div>
        )}
        {discount > 0 && (
          <div className="flex justify-between text-green-600">
            <span className="flex items-center gap-1">
              <Tag size={14} /> {t('discount')}
            </span>
            <span>- {formatAmount(discount)}</span>
          </div>
        )}
      </div>

      {/* Total */}
      <div className="flex justify-between py-4 border-b border-gray-100">
        <span className="font-semibold text-dark">{t('total')}</span>
        <span className="font-bold text-xl text-primary">{formatAmount(total)}</span>
      </div>

      {/* Savings */}
      {discount > 0 && (
        <div className="mt-3 p-3 bg-green-50 rounded-lg">
          <p className="text-sm text-green-700 flex items-center gap-2">
            <Gift size={16} />
            {t('youSaved', { amount: formatAmount(discount) })}
          </p>
        </div>
      )}

      {/* Coupon Section */}
      {!appliedCouponCode && onApplyCoupon && (
        <div className="mt-4">
          <label className="block text-sm font-medium text-dark mb-2">{t('couponCode')}</label>
          <div className="flex gap-2">
            <input
              type="text"
              value={couponCode}
              onChange={(e) => setCouponCode(e.target.value.toUpperCase())}
              placeholder={t('enterCode')}
              disabled={isApplying}
              className="flex-1 px-3 py-2 border border-gray-200 rounded-lg focus:border-primary focus:ring-1 focus:ring-primary outline-none text-sm disabled:opacity-50"
            />
            <button
              onClick={handleApplyCoupon}
              disabled={isApplying}
              className="px-4 py-2 border border-primary text-primary rounded-lg text-sm font-medium hover:bg-primary hover:text-white transition disabled:opacity-50"
            >
              {t('apply')}
            </button>
          </div>
          {couponError && <p className="text-red-500 text-xs mt-1">{couponError}</p>}
        </div>
      )}

      {appliedCouponCode && (
        <div className="mt-4 p-2 bg-green-50 rounded-lg text-sm text-green-700">
          <div className="flex items-center justify-between">
            <span>
              {appliedCoupon && !appliedCoupon.appliesToAll
                ? appliedCoupon.type === 'percentage'
                  ? t('couponAppliedPercentageScoped', { code: appliedCouponCode, percent: appliedCoupon.value })
                  : t('couponAppliedFixedScoped', { code: appliedCouponCode, amount: formatAmount(appliedCoupon.value) })
                : t('couponApplied', { code: appliedCouponCode })}
            </span>
            <button onClick={() => onRemoveCoupon?.()} className="text-green-700 hover:text-red-500 shrink-0 ml-2" aria-label={t('removeCoupon')}>
              <X size={14} />
            </button>
          </div>
        </div>
      )}

      {/* Delivery Info */}
      <div className="mt-6 space-y-2 text-sm">
        {freeDeliveryThreshold > 0 && (
          <div className="flex items-center gap-2 text-gray-custom">
            <Truck size={16} />
            <span>{t('freeDeliveryAbove', { amount: formatAmount(freeDeliveryThreshold) })}</span>
          </div>
        )}
        <div className="flex items-center gap-2 text-gray-custom">
          <Shield size={16} />
          <span>{t('freshnessGuaranteed')}</span>
        </div>
        <div className="flex items-center gap-2 text-gray-custom">
          <Lock size={16} />
          <span>{t('secureCheckout')}</span>
        </div>
      </div>

      {isCheckoutDisabled && blockedReason && (
        <p className="mt-3 text-xs text-red-500 text-center">{blockedReason}</p>
      )}

      {/* Checkout Button */}
      <button
        onClick={onProceedToCheckout}
        disabled={isCheckoutDisabled}
        className="w-full mt-6 bg-gradient-primary text-white py-3 rounded-lg font-semibold flex items-center justify-center gap-2 hover:shadow-md transition disabled:opacity-50"
      >
        <CreditCard size={18} />
        {t('proceedToCheckout')}
      </button>
    </motion.div>
  )
}
