/**
 * Bundle Display Component
 *
 * Displays an AI-generated product bundle with explicit lifecycle-aware UI for
 * per-item swap/remove and rebuild/add actions.
 *
 * @package BoostBot
 * @since 1.0.0
 * @updated 1.9.0
 */

import { motion } from 'framer-motion'
import {
  ExternalLink,
  Loader2,
  Package,
  Percent,
  RefreshCw,
  ShoppingCart,
  Star,
  Trash2,
  Shuffle,
} from 'lucide-react'
import { t } from '@/lib/i18n'
import { adjustColor, resolveValue, type GlobalValues, type FieldValue } from '@/utils/resolveAppearance'

export interface BundleProduct {
  id: number
  name: string
  price: number
  original_price: number
  regular_price?: number
  image: string
  permalink: string
  rating: number
  on_sale: boolean
  score?: number
  savings?: number
}

export interface BundleCoupon {
  id: number
  code: string
  discount_type: string
  amount: number
}

export interface BundleData {
  bundle_id: number
  products: BundleProduct[]
  total_price: number
  original_price: number
  savings: number
  savings_percent: number
  add_to_cart_url?: string
  message?: string
  coupon?: BundleCoupon
}

export type BundleActionState = 'idle' | 'swapping' | 'rebuilding' | 'adding'

export interface BundleBuilderButtonSettings {
  background?: FieldValue
  color?: FieldValue
  borderColor?: FieldValue
  borderRadius?: FieldValue
  hoverBackground?: FieldValue
  fontSize?: FieldValue
}

export interface BundleBuilderWidgetSettings {
  container?: {
    background?: FieldValue
    borderRadius?: FieldValue
    shadow?: FieldValue
    borderColor?: FieldValue
  }
  header?: {
    background?: FieldValue
    textColor?: FieldValue
    subtitleColor?: FieldValue
    titleFontSize?: FieldValue
    titleFontWeight?: FieldValue
    subtitleFontSize?: FieldValue
  }
  productItem?: {
    background?: FieldValue
    textColor?: FieldValue
    mutedTextColor?: FieldValue
    priceColor?: FieldValue
    actionColor?: FieldValue
    borderRadius?: FieldValue
    nameFontSize?: FieldValue
    priceFontSize?: FieldValue
  }
  priceDisplay?: {
    originalPriceColor?: FieldValue
    discountedPriceColor?: FieldValue
    savingsBackground?: FieldValue
    savingsColor?: FieldValue
    savingsBorderRadius?: FieldValue
    couponBackground?: FieldValue
    couponColor?: FieldValue
  }
  summary?: {
    background?: FieldValue
    borderColor?: FieldValue
    labelColor?: FieldValue
    totalLabelColor?: FieldValue
    linkColor?: FieldValue
  }
  button?: BundleBuilderButtonSettings
  primaryButton?: BundleBuilderButtonSettings
  secondaryButton?: BundleBuilderButtonSettings
  swapButton?: BundleBuilderButtonSettings
  removeButton?: BundleBuilderButtonSettings
  states?: {
    loadingBackground?: FieldValue
    loadingIconColor?: FieldValue
    emptyBackground?: FieldValue
    emptyIconColor?: FieldValue
    errorBackground?: FieldValue
    errorIconColor?: FieldValue
    successBackground?: FieldValue
    successIconColor?: FieldValue
    titleColor?: FieldValue
    descriptionColor?: FieldValue
  }
}

interface BundleDisplayProps {
  bundle: BundleData
  widgetSettings?: BundleBuilderWidgetSettings
  globalValues?: GlobalValues
  onAddToCart?: () => void
  onRebuild?: () => void
  onSwapProduct?: (productId: number) => void
  onRemoveProduct?: (productId: number) => void
  onProductClick?: (productId: number) => void
  isRtl?: boolean
  primaryColor?: string
  actionState?: BundleActionState
  activeProductId?: number | null
  feedbackMessage?: string | null
  currencySymbol?: string
  language?: string
}

export function BundleDisplay({
  bundle,
  widgetSettings,
  globalValues,
  onAddToCart,
  onRebuild,
  onSwapProduct,
  onRemoveProduct,
  onProductClick,
  isRtl = true,
  primaryColor = '#3BC2D0',
  actionState = 'idle',
  activeProductId = null,
  feedbackMessage = null,
  currencySymbol: currencyProp,
  language,
}: BundleDisplayProps) {
  const normalizedLanguage = (language || '').toLowerCase().replace(/[-_].*$/, '')
  const currencyByLanguage =
    (window as any).boostbot_config?.woocommerce_currency_by_language
    || (window as any).boostbot_config?.woocommerce?.currency_by_language
  const currencySymbol = currencyProp
    || currencyByLanguage?.[normalizedLanguage]
    || (window as any).boostbot_config?.woocommerce?.currency_symbol
    || (normalizedLanguage === 'en' ? '$' : '₪')
  const rv = (field: FieldValue | undefined, fallback: string) => resolveValue(field, globalValues, fallback)
  const busy = actionState !== 'idle'
  const actionLabel = actionState === 'swapping'
    ? t('Updating bundle...')
    : actionState === 'rebuilding'
      ? t('Building your bundle...')
      : actionState === 'adding'
        ? t('Adding...')
        : ''

  const containerBackground = rv(widgetSettings?.container?.background, '#FFFFFF')
  const containerRadius = rv(widgetSettings?.container?.borderRadius, '16px')
  const containerShadow = rv(widgetSettings?.container?.shadow, '0 10px 24px rgba(15, 23, 42, 0.12)')
  const containerBorder = rv(widgetSettings?.container?.borderColor, '#E5E7EB')
  const headerBase = rv(widgetSettings?.header?.background, primaryColor)
  const headerText = rv(widgetSettings?.header?.textColor, '#FFFFFF')
  const headerSubtitle = rv(widgetSettings?.header?.subtitleColor, 'rgba(255,255,255,0.82)')
  const itemBackground = rv(widgetSettings?.productItem?.background, '#F8FAFC')
  const itemText = rv(widgetSettings?.productItem?.textColor, '#111827')
  const itemMuted = rv(widgetSettings?.productItem?.mutedTextColor, '#6B7280')
  const itemPrice = rv(widgetSettings?.productItem?.priceColor, primaryColor)
  const itemAction = rv(widgetSettings?.productItem?.actionColor, '#475569')
  const itemRadius = rv(widgetSettings?.productItem?.borderRadius, '12px')
  const summaryBackground = rv(widgetSettings?.summary?.background, '#F8FAFC')
  const summaryBorder = rv(widgetSettings?.summary?.borderColor, '#E5E7EB')
  const summaryLabel = rv(widgetSettings?.summary?.labelColor, '#64748B')
  const summaryTotalLabel = rv(widgetSettings?.summary?.totalLabelColor, '#0F172A')
  const linkColor = rv(widgetSettings?.summary?.linkColor, '#64748B')
  const savingsBackground = rv(widgetSettings?.priceDisplay?.savingsBackground, '#DCFCE7')
  const savingsColor = rv(widgetSettings?.priceDisplay?.savingsColor, '#166534')
  const couponBackground = rv(widgetSettings?.priceDisplay?.couponBackground, '#F3E8FF')
  const couponColor = rv(widgetSettings?.priceDisplay?.couponColor, '#7E22CE')

  const getButtonStyles = (settings: BundleBuilderButtonSettings | undefined, fallback: {
    background: string
    color: string
    borderColor: string
    radius: string
    fontSize: string
  }) => ({
    backgroundColor: rv(settings?.background, fallback.background),
    color: rv(settings?.color, fallback.color),
    borderColor: rv(settings?.borderColor, fallback.borderColor),
    borderRadius: rv(settings?.borderRadius, fallback.radius),
    fontSize: rv(settings?.fontSize, fallback.fontSize),
  })

  const primaryButton = getButtonStyles(widgetSettings?.primaryButton || widgetSettings?.button, {
    background: primaryColor,
    color: '#FFFFFF',
    borderColor: primaryColor,
    radius: '12px',
    fontSize: '14px',
  })
  const secondaryButton = getButtonStyles(widgetSettings?.secondaryButton, {
    background: '#FFFFFF',
    color: '#334155',
    borderColor: '#CBD5E1',
    radius: '12px',
    fontSize: '13px',
  })
  const swapButton = getButtonStyles(widgetSettings?.swapButton, {
    background: '#FFFFFF',
    color: itemAction,
    borderColor: '#CBD5E1',
    radius: '9999px',
    fontSize: '12px',
  })
  const removeButton = getButtonStyles(widgetSettings?.removeButton, {
    background: '#FFF1F2',
    color: '#BE123C',
    borderColor: '#FECDD3',
    radius: '9999px',
    fontSize: '12px',
  })

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      dir={isRtl ? 'rtl' : 'ltr'}
      style={{
        background: containerBackground,
        borderRadius: containerRadius,
        boxShadow: containerShadow,
        border: `1px solid ${containerBorder}`,
        overflow: 'hidden',
        maxWidth: '360px',
        marginInline: 'auto',
      }}
    >
      <div
        style={{
          background: `linear-gradient(135deg, ${headerBase}, ${adjustColor(headerBase, -20)})`,
          color: headerText,
          padding: '16px',
        }}
      >
        <h3
          className="flex items-center gap-2"
          style={{
            margin: 0,
            fontSize: rv(widgetSettings?.header?.titleFontSize, '18px'),
            fontWeight: rv(widgetSettings?.header?.titleFontWeight, '700'),
            color: headerText,
          }}
        >
          <span aria-hidden="true">🎁</span>
          <span>{bundle.message || t('The perfect bundle for you!')}</span>
        </h3>
        <p
          style={{
            margin: '6px 0 0',
            fontSize: rv(widgetSettings?.header?.subtitleFontSize, '12px'),
            color: headerSubtitle,
          }}
        >
          {t('{count} products selected just for you').replace('{count}', String(bundle.products.length))}
        </p>
      </div>

      {(busy || feedbackMessage) && (
        <div
          className="flex items-center gap-2"
          style={{
            padding: '10px 14px',
            background: rv(widgetSettings?.states?.loadingBackground, '#EFF6FF'),
            color: feedbackMessage ? rv(widgetSettings?.states?.descriptionColor, '#991B1B') : rv(widgetSettings?.states?.titleColor, '#1E3A8A'),
            borderBottom: `1px solid ${summaryBorder}`,
            fontSize: '12px',
            fontWeight: 600,
          }}
        >
          {busy && <Loader2 className="h-4 w-4 animate-spin" style={{ color: rv(widgetSettings?.states?.loadingIconColor, primaryColor) }} />}
          <span>{feedbackMessage || actionLabel}</span>
        </div>
      )}

      <div className="space-y-3" style={{ padding: '14px', maxHeight: '320px', overflowY: 'auto' }}>
        {bundle.products.map((product, idx) => {
          const rowBusy = activeProductId === product.id && actionState === 'swapping'

          return (
            <motion.div
              key={`${product.id}-${idx}`}
              initial={{ opacity: 0, x: isRtl ? 18 : -18 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: idx * 0.05 }}
              style={{
                background: itemBackground,
                borderRadius: itemRadius,
                padding: '10px',
                border: `1px solid ${busy && activeProductId === product.id ? adjustColor(containerBorder, -10) : 'transparent'}`,
                opacity: actionState === 'swapping' && activeProductId !== product.id ? 0.75 : 1,
              }}
            >
              <div className="flex items-center gap-3">
                <button
                  type="button"
                  onClick={() => onProductClick?.(product.id)}
                  style={{
                    width: '48px',
                    height: '48px',
                    borderRadius: '12px',
                    overflow: 'hidden',
                    flexShrink: 0,
                    background: '#E5E7EB',
                    border: 'none',
                    padding: 0,
                    cursor: onProductClick ? 'pointer' : 'default',
                  }}
                >
                  {product.image ? (
                    <img
                      src={product.image}
                      alt={product.name}
                      className="h-full w-full object-cover"
                      loading="lazy"
                    />
                  ) : (
                    <span className="flex h-full w-full items-center justify-center">
                      <Package className="h-5 w-5 text-gray-400" />
                    </span>
                  )}
                </button>

                <div className="min-w-0 flex-1">
                  <button
                    type="button"
                    onClick={() => onProductClick?.(product.id)}
                    className="w-full truncate text-start"
                    style={{
                      background: 'transparent',
                      border: 'none',
                      padding: 0,
                      cursor: onProductClick ? 'pointer' : 'default',
                      fontWeight: 600,
                      fontSize: rv(widgetSettings?.productItem?.nameFontSize, '14px'),
                      color: itemText,
                    }}
                  >
                    {product.name}
                  </button>
                  {product.rating > 0 && (
                    <div className="mt-1 flex items-center gap-1 text-xs" style={{ color: itemMuted }}>
                      <Star className="h-3 w-3 fill-current text-yellow-500" />
                      <span>{product.rating.toFixed(1)}</span>
                    </div>
                  )}
                </div>

                <div className="shrink-0 text-end">
                  <div
                    style={{
                      fontWeight: 700,
                      fontSize: rv(widgetSettings?.productItem?.priceFontSize, '14px'),
                      color: itemPrice,
                    }}
                  >
                    {currencySymbol}{product.price.toFixed(0)}
                  </div>
                  {product.original_price > product.price && (
                    <div
                      style={{
                        fontSize: '11px',
                        color: rv(widgetSettings?.priceDisplay?.originalPriceColor, itemMuted),
                        textDecoration: 'line-through',
                      }}
                    >
                      {currencySymbol}{product.original_price.toFixed(0)}
                    </div>
                  )}
                </div>
              </div>

              {(onSwapProduct || onRemoveProduct) && (
                <div className="mt-3 flex items-center justify-end gap-2">
                  {onSwapProduct && (
                    <motion.button
                      type="button"
                      onClick={() => onSwapProduct(product.id)}
                      disabled={busy}
                      title={t('Swap item')}
                      className="flex items-center gap-1.5 disabled:cursor-not-allowed disabled:opacity-60"
                      style={{
                        ...swapButton,
                        borderWidth: '1px',
                        borderStyle: 'solid',
                        padding: '6px 10px',
                      }}
                      whileHover={{ scale: busy ? 1 : 1.02 }}
                      whileTap={{ scale: busy ? 1 : 0.98 }}
                    >
                      {rowBusy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Shuffle className="h-3.5 w-3.5" />}
                      <span>{rowBusy ? t('Updating...') : t('Swap')}</span>
                    </motion.button>
                  )}
                  {onRemoveProduct && (
                    <motion.button
                      type="button"
                      onClick={() => onRemoveProduct(product.id)}
                      disabled={busy || bundle.products.length <= 1}
                      title={t('Remove item')}
                      className="flex items-center gap-1.5 disabled:cursor-not-allowed disabled:opacity-60"
                      style={{
                        ...removeButton,
                        borderWidth: '1px',
                        borderStyle: 'solid',
                        padding: '6px 10px',
                      }}
                      whileHover={{ scale: busy ? 1 : 1.02 }}
                      whileTap={{ scale: busy ? 1 : 0.98 }}
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                      <span>{t('Remove')}</span>
                    </motion.button>
                  )}
                </div>
              )}
            </motion.div>
          )
        })}
      </div>

      <div
        style={{
          borderTop: `1px solid ${summaryBorder}`,
          background: summaryBackground,
          padding: '14px',
        }}
      >
        <div className="mb-2 flex items-center justify-between">
          <span style={{ color: summaryLabel, fontSize: '13px' }}>{t('Original price:')}</span>
          <span
            style={{
              color: rv(widgetSettings?.priceDisplay?.originalPriceColor, '#94A3B8'),
              textDecoration: 'line-through',
              fontSize: '13px',
            }}
          >
            {currencySymbol}{bundle.original_price.toFixed(0)}
          </span>
        </div>

        <div className="mb-3 flex items-center justify-between">
          <span style={{ color: summaryTotalLabel, fontSize: '15px', fontWeight: 700 }}>{t('Bundle price:')}</span>
          <span
            style={{
              color: rv(widgetSettings?.priceDisplay?.discountedPriceColor, primaryColor),
              fontSize: '22px',
              fontWeight: 800,
            }}
          >
            {currencySymbol}{bundle.total_price.toFixed(0)}
          </span>
        </div>

        {bundle.savings > 0 && (
          <div
            className="mb-3 flex items-center justify-center gap-2"
            style={{
              background: savingsBackground,
              borderRadius: rv(widgetSettings?.priceDisplay?.savingsBorderRadius, '9999px'),
              color: savingsColor,
              padding: '8px 12px',
            }}
          >
            <Percent className="h-4 w-4" />
            <span style={{ fontSize: '13px', fontWeight: 700 }}>
              {t('Save')} {currencySymbol}{bundle.savings.toFixed(0)} ({bundle.savings_percent.toFixed(0)}%)
            </span>
          </div>
        )}

        {bundle.coupon && (
          <div
            className="mb-4 flex items-center justify-center gap-2"
            style={{
              background: couponBackground,
              color: couponColor,
              borderRadius: '12px',
              padding: '8px 10px',
            }}
          >
            <span aria-hidden="true">🎟️</span>
            <span style={{ fontSize: '12px', fontWeight: 600 }}>
              {t('Coupon "{code}" applied automatically!').replace('{code}', bundle.coupon.code)}
              {' '}
              ({bundle.coupon.amount}{bundle.coupon.discount_type === 'percent' ? '%' : currencySymbol} {t('extra discount')})
            </span>
          </div>
        )}

        <div className="flex gap-2">
          {onAddToCart && (
            <motion.button
              type="button"
              onClick={onAddToCart}
              disabled={busy}
              className="flex flex-1 items-center justify-center gap-2 disabled:cursor-not-allowed disabled:opacity-60"
              style={{
                ...primaryButton,
                borderWidth: '1px',
                borderStyle: 'solid',
                padding: '12px 14px',
                fontWeight: 700,
              }}
              whileHover={{ scale: busy ? 1 : 1.01 }}
              whileTap={{ scale: busy ? 1 : 0.99 }}
            >
              {actionState === 'adding' ? <Loader2 className="h-4 w-4 animate-spin" /> : <ShoppingCart className="h-4 w-4" />}
              <span>{actionState === 'adding' ? t('Adding...') : t('Add to cart')}</span>
            </motion.button>
          )}

          {onRebuild && (
            <motion.button
              type="button"
              onClick={onRebuild}
              disabled={busy}
              className="flex items-center justify-center gap-2 disabled:cursor-not-allowed disabled:opacity-60"
              style={{
                ...secondaryButton,
                borderWidth: '1px',
                borderStyle: 'solid',
                padding: '12px 14px',
                fontWeight: 600,
                minWidth: '136px',
              }}
              whileHover={{ scale: busy ? 1 : 1.01 }}
              whileTap={{ scale: busy ? 1 : 0.99 }}
            >
              {actionState === 'rebuilding' ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
              <span>{actionState === 'rebuilding' ? t('Refreshing...') : t('Another bundle')}</span>
            </motion.button>
          )}
        </div>

        {bundle.add_to_cart_url && (
          <a
            href={bundle.add_to_cart_url}
            target="_blank"
            rel="noopener noreferrer"
            className="mt-3 flex items-center justify-center gap-2 transition-colors"
            style={{
              color: linkColor,
              fontSize: '12px',
              textDecoration: 'none',
            }}
          >
            <ExternalLink className="h-4 w-4" />
            <span>{t('Open in store')}</span>
          </a>
        )}
      </div>
    </motion.div>
  )
}

export default BundleDisplay



