import { motion } from 'framer-motion'
import { Minus, Plus, ShoppingCart, Trash2, X } from 'lucide-react'
import { useChatStore } from '@/store/chatStore'
import { flushCommerceEvents, getCartTelemetryFields, trackCommerceEvent } from '@/services/commerceTelemetry'
import { t } from '@/lib/i18n'
import { getWooCartCount } from '@/utils/cart'
import { getResolvedCartAppearance } from './cart/cartAppearance'

export function CartDrawer() {
  const {
    config,
    conversationId,
    visitorId,
    currentBotId,
    cart,
    isCartLoading,
    cartError,
    closeCart,
    updateCartItemAndSync,
    removeCartItemAndSync,
  } = useChatStore()
  const isRtl = window.boostbot_config?.is_rtl ?? true
  const appearance = getResolvedCartAppearance(config)
  const items = cart?.items ?? []
  const cartCount = getWooCartCount(cart)
  const isEmpty = !cart || cart.is_empty || cartCount <= 0 || items.length === 0

  const emitDrawerEvent = (event: Parameters<typeof trackCommerceEvent>[0], eventCart = cart) => {
    trackCommerceEvent({
      conversation_id: conversationId,
      visitor_id: visitorId,
      bot_id: currentBotId,
      language: config.language,
      widget_type: 'cart',
      ...getCartTelemetryFields(eventCart),
      ...event,
      metadata: {
        source: 'drawer',
        ...(event.metadata || {}),
      },
    })
  }

  const handleRemoveItem = async (itemKey: string) => {
    const previousItem = cart?.items.find((item) => item.key === itemKey)
    const result = await removeCartItemAndSync(itemKey)
    if (result.success) {
      emitDrawerEvent(
        {
          event_type: 'cart_item_removed',
          product_id: previousItem?.id ?? null,
          product_name: previousItem?.name ?? null,
          variation_id: previousItem?.variation_id ?? null,
          quantity: previousItem?.quantity ?? null,
          cart_item_key: itemKey,
        },
        result.cart,
      )
    }
  }

  const handleUpdateQuantity = async (itemKey: string, quantity: number) => {
    const previousItem = cart?.items.find((item) => item.key === itemKey)
    const result = await updateCartItemAndSync(itemKey, quantity)
    if (result.success) {
      emitDrawerEvent(
        {
          event_type: 'cart_item_quantity_updated',
          product_id: previousItem?.id ?? null,
          product_name: previousItem?.name ?? null,
          variation_id: previousItem?.variation_id ?? null,
          quantity,
          cart_item_key: itemKey,
        },
        result.cart,
      )
    }
  }

  const handleCheckoutClick = () => {
    const checkoutUrl = cart?.checkout_url || '#'
    const hasWooSessionCookie = typeof document !== 'undefined'
      && (
        document.cookie.includes('woocommerce_cart_hash=')
        || document.cookie.includes('wp_woocommerce_session_')
      )

    console.log('[BoostBot] Checkout redirect:', {
      url: checkoutUrl,
      chatCartItems: cart?.items?.length ?? 0,
      cart_count: cartCount,
      cookies: hasWooSessionCookie,
      source: 'drawer',
    })

    emitDrawerEvent({ event_type: 'checkout_clicked' }, cart)
    void flushCommerceEvents({ transport: 'beacon' })
  }

  return (
    <motion.div
      className="flex h-full flex-col"
      dir={isRtl ? 'rtl' : 'ltr'}
      initial={{ opacity: 0, x: isRtl ? -18 : 18 }}
      animate={{ opacity: 1, x: 0 }}
      exit={{ opacity: 0, x: isRtl ? -18 : 18 }}
      transition={{ duration: 0.2 }}
      style={{
        background: appearance.drawer.background,
        borderColor: appearance.drawer.borderColor,
        borderRadius: appearance.drawer.borderRadius,
        boxShadow: appearance.drawer.shadow,
      }}
    >
      <div
        className="flex items-center justify-between border-b px-4 py-4"
        style={{ background: appearance.header.background, borderColor: appearance.drawer.borderColor }}
      >
        <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.header.color }}>{t('Your cart')}</p>
            <p className="text-xs" style={{ color: appearance.summary.labelColor }}>
              {cartCount} {t('items')}
            </p>
          </div>
        </div>

        <div className="flex items-center gap-2">
          {!isEmpty && (
            <span
              className="inline-flex items-center justify-center rounded-full px-2.5 py-1 text-xs font-semibold"
              style={{ background: appearance.header.countBackground, color: appearance.header.countColor }}
            >
              {cartCount}
            </span>
          )}
          <button
            type="button"
            onClick={closeCart}
            className="rounded-full p-2 transition-opacity hover:opacity-80"
            aria-label={t('Close cart')}
            style={{ color: appearance.header.color }}
          >
            <X className="h-4 w-4" />
          </button>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto px-4 py-4">
        {isCartLoading && (
          <div className="pb-3 text-xs" style={{ color: appearance.summary.labelColor }}>
            {t('Updating cart...')}
          </div>
        )}

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

        {isEmpty ? (
          <div className="flex h-full min-h-[240px] flex-col items-center justify-center gap-3 text-center">
            <ShoppingCart className="h-12 w-12" style={{ color: appearance.empty.iconColor }} />
            <p className="text-sm font-semibold" style={{ color: appearance.empty.titleColor }}>{t('Cart is empty')}</p>
            <p className="text-xs" style={{ color: appearance.empty.descriptionColor }}>{t('Add products to continue')}</p>
          </div>
        ) : (
          <div className="space-y-3">
            {items.map((item) => (
              <div
                key={item.key}
                className="rounded-2xl border p-3"
                style={{
                  background: appearance.item.background,
                  borderColor: appearance.item.borderColor,
                  borderRadius: appearance.item.borderRadius,
                }}
              >
                <div className="flex items-start gap-3">
                  {item.image ? (
                    <img src={item.image} alt={item.name} className="h-14 w-14 rounded-xl object-cover" />
                  ) : (
                    <div className="h-14 w-14 rounded-xl bg-slate-100" />
                  )}

                  <div className="min-w-0 flex-1">
                    <div className="flex items-start justify-between gap-3">
                      <div>
                        <p className="text-sm font-semibold leading-5" style={{ color: appearance.item.titleColor }}>
                          {item.name}
                        </p>
                        <p className="mt-1 text-xs" style={{ color: appearance.item.metaColor }}>
                          {item.price_display || item.price}
                        </p>
                      </div>

                      <button
                        type="button"
                        onClick={() => void handleRemoveItem(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={() => void handleUpdateQuantity(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={() => void handleUpdateQuantity(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>

                      <p className="text-sm font-semibold" style={{ color: appearance.item.priceColor }}>
                        {item.subtotal_display || item.subtotal}
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      <div className="border-t px-4 py-4" style={{ borderColor: appearance.drawer.borderColor }}>
        {!isEmpty && (
          <div
            className="mb-3 rounded-2xl border px-4 py-3"
            style={{
              background: appearance.summary.background,
              borderColor: appearance.summary.borderColor,
              borderRadius: appearance.summary.borderRadius,
            }}
          >
            <div className="flex items-center justify-between text-sm">
              <span style={{ color: appearance.summary.labelColor }}>{t('Total')}</span>
              <span className="font-semibold" style={{ color: appearance.summary.valueColor }}>
                {cart?.total ?? ''}
              </span>
            </div>
          </div>
        )}

        <div className="flex gap-2">
          {!isEmpty && (
            <a
              href={cart?.checkout_url || '#'}
              onClick={handleCheckoutClick}
              className="flex-1 rounded-xl px-4 py-3 text-center text-sm font-semibold transition-opacity hover:opacity-90"
              style={{
                background: appearance.actions.primaryBackground,
                color: appearance.actions.primaryColor,
                borderRadius: appearance.actions.borderRadius,
              }}
            >
              {t('Checkout')}
            </a>
          )}
          <button
            type="button"
            onClick={closeCart}
            className="rounded-xl border px-4 py-3 text-sm font-semibold transition-colors hover:opacity-90"
            style={{
              background: appearance.actions.secondaryBackground,
              color: appearance.actions.secondaryColor,
              borderColor: appearance.actions.secondaryBorderColor,
              borderRadius: appearance.actions.borderRadius,
            }}
          >
            {t('Continue chat')}
          </button>
        </div>
      </div>
    </motion.div>
  )
}

export default CartDrawer
