/**
 * Cart Widget
 *
 * Shows cart status and in-widget mutations.
 */

import { motion } from 'framer-motion'
import { Minus, Package, Plus, ShoppingCart, Trash2 } from 'lucide-react'
import { t } from '@/lib/i18n'
import { useChatStore } from '@/store/chatStore'
import { getWooCartCount } from '@/utils/cart'
import { getResolvedCartAppearance } from '@/components/cart/cartAppearance'
import type { WooCart } from '@/types'

interface CartWidgetProps {
  config: WooCart & { is_rtl?: boolean }
  language?: string
  onCheckout?: () => void
  onViewCart?: () => void
  onRemoveItem?: (itemKey: string) => void
  onUpdateItem?: (itemKey: string, quantity: number) => void
}

export function CartWidget({ config, language, onCheckout, onViewCart, onRemoveItem, onUpdateItem }: CartWidgetProps) {
  const { config: chatConfig, isCartLoading, cartError } = useChatStore()
  const appearance = getResolvedCartAppearance(chatConfig)
  const resolvedIsRtl = typeof config.is_rtl === 'boolean' ? config.is_rtl : language !== 'en'
  const { total, items, checkout_url, cart_url, is_empty } = config
  const count = getWooCartCount(config)

  return (
    <motion.div
      className="rounded-2xl border p-4"
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      dir={resolvedIsRtl ? 'rtl' : 'ltr'}
      style={{
        background: appearance.drawer.background,
        borderColor: appearance.drawer.borderColor,
        borderRadius: appearance.drawer.borderRadius,
        boxShadow: appearance.drawer.shadow,
      }}
    >
      <div className="mb-4 flex items-center justify-between gap-3">
        <div className="flex items-center gap-3">
          <div
            className="flex h-10 w-10 items-center justify-center rounded-full"
            style={{ background: appearance.badge.background, color: appearance.badge.iconColor }}
          >
            <ShoppingCart className="h-5 w-5" />
          </div>
          <div>
            <p className="text-sm font-semibold" style={{ color: appearance.item.titleColor }}>
              {is_empty ? t('Cart is empty') : `${count} ${count === 1 ? t('item') : t('items')} ${t('in cart')}`}
            </p>
            <p className="text-xs" style={{ color: appearance.item.metaColor }}>
              {is_empty ? t('Add products to continue') : `${t('Total:')} ${total}`}
            </p>
          </div>
        </div>
      </div>

      {cartError && (
        <div className="mb-3 rounded-xl border px-3 py-2 text-xs" style={{ borderColor: '#FCA5A5', color: '#B91C1C' }}>
          {cartError}
        </div>
      )}

      {is_empty ? (
        <div className="py-6 text-center">
          <ShoppingCart className="mx-auto mb-3 h-12 w-12" style={{ color: appearance.empty.iconColor }} />
          <p className="text-sm font-medium" style={{ color: appearance.empty.titleColor }}>{t('Cart is empty')}</p>
          <p className="mt-1 text-xs" style={{ color: appearance.empty.descriptionColor }}>{t('Add products to continue')}</p>
        </div>
      ) : (
        <>
          <div className="mb-4 space-y-2">
            {items.slice(0, 3).map((item, index) => (
              <motion.div
                key={item.key}
                className="rounded-xl border p-3"
                initial={{ opacity: 0, x: resolvedIsRtl ? 10 : -10 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: index * 0.06 }}
                style={{
                  background: appearance.item.background,
                  borderColor: appearance.item.borderColor,
                  borderRadius: appearance.item.borderRadius,
                }}
              >
                <div className="flex items-center gap-3">
                  {item.image ? (
                    <img src={item.image} alt={item.name} className="h-10 w-10 rounded-lg object-cover" />
                  ) : (
                    <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-gray-100">
                      <Package className="h-5 w-5 text-gray-400" />
                    </div>
                  )}
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-sm font-medium" style={{ color: appearance.item.titleColor }}>{item.name}</p>
                    <p className="text-xs" style={{ color: appearance.item.metaColor }}>{item.price_display || item.price}</p>
                  </div>
                  {onRemoveItem && (
                    <button
                      type="button"
                      onClick={() => onRemoveItem(item.key)}
                      className="rounded-full p-1.5 transition-opacity hover:opacity-80"
                      aria-label={t('Remove item')}
                      style={{ color: appearance.item.removeColor }}
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  )}
                </div>

                <div className="mt-3 flex items-center justify-between gap-3">
                  <div
                    className="inline-flex items-center gap-2 rounded-full px-2 py-1"
                    style={{ background: appearance.item.quantityBackground, color: appearance.item.quantityColor }}
                  >
                    <button
                      type="button"
                      onClick={() => onUpdateItem?.(item.key, item.quantity - 1)}
                      className="rounded-full p-1 transition-opacity hover:opacity-80"
                      aria-label={t('Decrease quantity')}
                    >
                      <Minus className="h-3.5 w-3.5" />
                    </button>
                    <span className="min-w-6 text-center text-xs font-semibold">{item.quantity}</span>
                    <button
                      type="button"
                      onClick={() => onUpdateItem?.(item.key, item.quantity + 1)}
                      className="rounded-full p-1 transition-opacity hover:opacity-80"
                      aria-label={t('Increase quantity')}
                    >
                      <Plus className="h-3.5 w-3.5" />
                    </button>
                  </div>
                  <span className="text-sm font-semibold" style={{ color: appearance.item.priceColor }}>
                    {item.subtotal_display || item.subtotal}
                  </span>
                </div>
              </motion.div>
            ))}

            {items.length > 3 && (
              <p className="text-center text-xs" style={{ color: appearance.item.metaColor }}>
                + {items.length - 3} {t('more items')}
              </p>
            )}
          </div>

          <div className="flex gap-2">
            <motion.a
              href={checkout_url}
              onClick={onCheckout}
              className="flex-1 rounded-xl px-4 py-2.5 text-center text-sm font-semibold"
              whileHover={{ scale: 1.01 }}
              whileTap={{ scale: 0.99 }}
              style={{
                background: appearance.actions.primaryBackground,
                color: appearance.actions.primaryColor,
                borderRadius: appearance.actions.borderRadius,
                opacity: isCartLoading ? 0.7 : 1,
              }}
            >
              {t('Checkout')}
            </motion.a>

            <motion.a
              href={cart_url}
              onClick={onViewCart}
              className="rounded-xl border px-4 py-2.5 text-sm font-semibold"
              whileHover={{ scale: 1.01 }}
              whileTap={{ scale: 0.99 }}
              style={{
                background: appearance.actions.secondaryBackground,
                color: appearance.actions.secondaryColor,
                borderColor: appearance.actions.secondaryBorderColor,
                borderRadius: appearance.actions.borderRadius,
              }}
            >
              {t('View cart')}
            </motion.a>
          </div>
        </>
      )}
    </motion.div>
  )
}

export default CartWidget








