/**
 * Bundle Builder Settings Component (Simplified)
 * 
 * Streamlined settings for the Bundle Builder widget.
 * AI handles discovery naturally through conversation.
 * 
 * @package BoostBot
 * @since 1.2.0
 */

import { useState } from 'react'
import {
  Package, Settings, Percent, Tag, ChevronDown, ChevronUp,
  Plus, Trash2, Info
} from 'lucide-react'
import { t, getDirection } from '@/lib/i18n'
import { ProductSearchPicker } from '@/components/shared/ProductSearchPicker'

// Types
interface ProductSettings {
  mode: 'all' | 'categories' | 'specific'
  allowed_categories: (number | string)[]
  excluded_categories: (number | string)[]
  specific_product_ids: number[]
  preferred_product_ids: number[]
  excluded_product_ids: number[]
  include_on_sale: boolean
  include_variable: boolean
  min_products_in_bundle: number
  max_products_in_bundle: number
}

interface PricingSettings {
  discount_type: 'percent' | 'fixed' | 'tiered'
  discount_percent: number
  discount_fixed: number
  discount_tiers: Array<{ min_amount: number; max_amount: number | null; discount: number }>
  show_savings: boolean
}

interface CouponSettings {
  enabled: boolean
  auto_coupon_id: number | null
  auto_select_best: boolean
}

interface BundleBuilderConfig {
  product_settings: ProductSettings
  pricing_settings: PricingSettings
  coupon_settings: CouponSettings
  success_message: string
  empty_message: string
}

interface Category {
  id: number
  slug: string
  name: string
  count: number
}

interface Product {
  id: number
  name: string
  price: number
  image?: string
}

interface Coupon {
  id: number
  code: string
  discount_type: string
  amount: number
}

interface BundleBuilderSettingsProps {
  config: Partial<BundleBuilderConfig>
  onChange: (config: Partial<BundleBuilderConfig>) => void
  categories?: Category[]
  products?: Product[]
  coupons?: Coupon[]
  language?: string
}

// Default values
const DEFAULT_CONFIG: BundleBuilderConfig = {
  product_settings: {
    mode: 'all',
    allowed_categories: [],
    excluded_categories: [],
    specific_product_ids: [],
    preferred_product_ids: [],
    excluded_product_ids: [],
    include_on_sale: true,
    include_variable: true,
    min_products_in_bundle: 2,
    max_products_in_bundle: 5,
  },
  pricing_settings: {
    discount_type: 'percent',
    discount_percent: 10,
    discount_fixed: 50,
    discount_tiers: [],
    show_savings: true,
  },
  coupon_settings: {
    enabled: false,
    auto_coupon_id: null,
    auto_select_best: false,
  },
  success_message: t('Bundle added to cart! 🎉'),
  empty_message: t('No matching products found'),
}

// Collapsible Section Component
function Section({
  title,
  icon: Icon,
  children,
  defaultOpen = false,
  badge,
}: {
  title: string
  icon: React.ElementType
  children: React.ReactNode
  defaultOpen?: boolean
  badge?: string
}) {
  const [isOpen, setIsOpen] = useState(defaultOpen)

  return (
    <div className="border border-gray-200 rounded-lg overflow-hidden mb-4">
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className="w-full flex items-center justify-between p-4 bg-gray-50 hover:bg-gray-100 transition-colors"
      >
        <div className="flex items-center gap-3">
          <Icon className="w-5 h-5 text-purple-600" />
          <span className="font-medium text-gray-900">{title}</span>
          {badge && (
            <span className="px-2 py-0.5 text-xs bg-purple-100 text-purple-700 rounded-full">
              {badge}
            </span>
          )}
        </div>
        {isOpen ? (
          <ChevronUp className="w-5 h-5 text-gray-500" />
        ) : (
          <ChevronDown className="w-5 h-5 text-gray-500" />
        )}
      </button>
      {isOpen && <div className="p-4 bg-white">{children}</div>}
    </div>
  )
}

// Input Components
function NumberInput({
  label,
  value,
  onChange,
  min,
  max,
  suffix,
  hint,
}: {
  label: string
  value: number | null
  onChange: (value: number | null) => void
  min?: number
  max?: number
  suffix?: string
  hint?: string
}) {
  return (
    <div className="mb-4">
      <label className="block text-sm font-medium text-gray-700 mb-1">{label}</label>
      <div className="flex items-center gap-2">
        <input
          type="number"
          value={value ?? ''}
          onChange={(e) => onChange(e.target.value ? Number(e.target.value) : null)}
          min={min}
          max={max}
          className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
        />
        {suffix && <span className="text-gray-500 text-sm whitespace-nowrap">{suffix}</span>}
      </div>
      {hint && <p className="mt-1 text-xs text-gray-500">{hint}</p>}
    </div>
  )
}

function Toggle({
  label,
  value,
  onChange,
  hint,
}: {
  label: string
  value: boolean
  onChange: (value: boolean) => void
  hint?: string
}) {
  return (
    <div className="flex items-center justify-between gap-4 py-3 border-b border-gray-100 last:border-0">
      <div className="flex-1">
        <span className="text-sm font-medium text-gray-700">{label}</span>
        {hint && <p className="text-xs text-gray-500 mt-0.5">{hint}</p>}
      </div>
      <button
        type="button"
        onClick={() => onChange(!value)}
        style={{
          width: '44px',
          height: '24px',
          borderRadius: '12px',
          backgroundColor: value ? '#9333ea' : '#d1d5db',
          position: 'relative',
          cursor: 'pointer',
          border: '2px solid',
          borderColor: value ? '#7c3aed' : '#9ca3af',
          flexShrink: 0,
          transition: 'background-color 0.2s, border-color 0.2s',
        }}
      >
        <span
          style={{
            position: 'absolute',
            top: '2px',
            width: '16px',
            height: '16px',
            backgroundColor: 'white',
            borderRadius: '50%',
            boxShadow: '0 1px 3px rgba(0,0,0,0.3)',
            transition: 'left 0.2s, right 0.2s',
            left: value ? '22px' : '2px',
          }}
        />
      </button>
    </div>
  )
}

function SelectInput({
  label,
  value,
  onChange,
  options,
  hint,
}: {
  label: string
  value: string
  onChange: (value: string) => void
  options: Array<{ value: string; label: string }>
  hint?: string
}) {
  return (
    <div className="mb-4">
      <label className="block text-sm font-medium text-gray-700 mb-1">{label}</label>
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
      >
        {options.map((opt) => (
          <option key={opt.value} value={opt.value}>
            {opt.label}
          </option>
        ))}
      </select>
      {hint && <p className="mt-1 text-xs text-gray-500">{hint}</p>}
    </div>
  )
}

function TextInput({
  label,
  value,
  onChange,
  placeholder,
  hint,
}: {
  label: string
  value: string
  onChange: (value: string) => void
  placeholder?: string
  hint?: string
}) {
  return (
    <div className="mb-4">
      <label className="block text-sm font-medium text-gray-700 mb-1">{label}</label>
      <input
        type="text"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
      />
      {hint && <p className="mt-1 text-xs text-gray-500">{hint}</p>}
    </div>
  )
}

// Main Component
export function BundleBuilderSettings({
  config: inputConfig,
  onChange,
  categories = [],
  products: _products = [],
  coupons = [],
  language,
}: BundleBuilderSettingsProps) {
  const currencySymbol = (window as any).boostbotAdmin?.woocommerce_currency_symbol || '₪'
  // Merge with defaults
  const config: BundleBuilderConfig = {
    ...DEFAULT_CONFIG,
    ...inputConfig,
    product_settings: { ...DEFAULT_CONFIG.product_settings, ...inputConfig.product_settings },
    pricing_settings: { ...DEFAULT_CONFIG.pricing_settings, ...inputConfig.pricing_settings },
    coupon_settings: { ...DEFAULT_CONFIG.coupon_settings, ...inputConfig.coupon_settings },
  }

  const updateConfig = (updates: Partial<BundleBuilderConfig>) => {
    onChange({ ...config, ...updates })
  }

  const updateProductSettings = (updates: Partial<ProductSettings>) => {
    updateConfig({
      product_settings: { ...config.product_settings, ...updates },
    })
  }

  const updatePricingSettings = (updates: Partial<PricingSettings>) => {
    updateConfig({
      pricing_settings: { ...config.pricing_settings, ...updates },
    })
  }

  const updateCouponSettings = (updates: Partial<CouponSettings>) => {
    updateConfig({
      coupon_settings: { ...config.coupon_settings, ...updates },
    })
  }

  return (
    <div className="space-y-4" dir={getDirection()}>
      {/* Header */}
      <div className="flex items-center gap-3 mb-6">
        <div className="p-2 bg-purple-100 rounded-lg">
          <Package className="w-6 h-6 text-purple-600" />
        </div>
        <div>
          <h2 className="text-lg font-bold text-gray-900">{t('AI Bundle Builder Settings')}</h2>
          <p className="text-sm text-gray-500">{t('AI will suggest bundles naturally during the conversation')}</p>
        </div>
      </div>

      {/* Info Box */}
      <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
        <div className="flex gap-3">
          <Info className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
          <div className="text-sm text-blue-800">
            <p className="font-medium mb-1">{t('How does it work?')}</p>
            <p className="text-blue-700">
              {t('AI gathers information about customer needs in natural conversation, and at the right moment presents a personalized bundle offer - just like it suggests other widgets.')}
            </p>
          </div>
        </div>
      </div>

      {/* Product Selection */}
      <Section title={t('Product Selection')} icon={Package} defaultOpen={true}>
        <SelectInput
          label={t('Selection Mode')}
          value={config.product_settings.mode}
          onChange={(v) => updateProductSettings({ mode: v as 'all' | 'categories' | 'specific' })}
          options={[
            { value: 'all', label: t('All products in store') },
            { value: 'categories', label: t('Selected categories') },
            { value: 'specific', label: t('Specific products') },
          ]}
          hint={t('Which products will be included in bundles')}
        />

        {config.product_settings.mode === 'categories' && categories.length > 0 && (
          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 mb-2">{t('Allowed Categories')}</label>
            <div className="flex flex-wrap gap-2">
              {categories.map((cat) => {
                const isSelected = config.product_settings.allowed_categories.some(
                  (c) => Number(c) === cat.id || c === cat.slug
                )
                return (
                  <button
                    type="button"
                    key={cat.id}
                    onClick={() => {
                      const newCats = isSelected
                        ? config.product_settings.allowed_categories.filter(
                            (c) => Number(c) !== cat.id && c !== cat.slug
                          )
                        : [...config.product_settings.allowed_categories, cat.id]
                      updateProductSettings({ allowed_categories: newCats })
                    }}
                    className={`px-3 py-1.5 rounded-full text-sm transition-colors cursor-pointer ${
                      isSelected
                        ? 'bg-purple-600 text-white'
                        : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                    }`}
                  >
                    {cat.name} ({cat.count})
                  </button>
                )
              })}
            </div>
          </div>
        )}

        {config.product_settings.mode === 'specific' && (
          <div className="mb-4">
            <ProductSearchPicker
              selectedIds={config.product_settings.specific_product_ids || []}
              onChange={(ids) => updateProductSettings({ specific_product_ids: ids })}
              label={t('Include Products')}
              language={language}
            />
          </div>
        )}

        <div className="grid grid-cols-2 gap-4">
          <NumberInput
            label={t('Minimum Products')}
            value={config.product_settings.min_products_in_bundle}
            onChange={(v) => updateProductSettings({ min_products_in_bundle: v || 2 })}
            min={1}
            max={10}
          />
          <NumberInput
            label={t('Maximum Products')}
            value={config.product_settings.max_products_in_bundle}
            onChange={(v) => updateProductSettings({ max_products_in_bundle: v || 5 })}
            min={2}
            max={20}
          />
        </div>

        <div className="border-t pt-4 mt-4">
          <Toggle
            label={t('Include on-sale products')}
            value={config.product_settings.include_on_sale}
            onChange={(v) => updateProductSettings({ include_on_sale: v })}
          />
          <Toggle
            label={t('Include variable products')}
            value={config.product_settings.include_variable}
            onChange={(v) => updateProductSettings({ include_variable: v })}
          />
        </div>

        {/* Preferred Products */}
        <div className="border-t pt-4 mt-4">
          <label className="block text-sm font-medium text-gray-700 mb-2">
            {t('Preferred Products')}
            <span className="text-xs text-gray-500 mr-2">{t('(will get priority)')}</span>
          </label>
          <ProductSearchPicker
            selectedIds={config.product_settings.preferred_product_ids}
            onChange={(ids) => updateProductSettings({ preferred_product_ids: ids })}
            language={language}
          />
        </div>
      </Section>

      {/* Pricing */}
      <Section title={t('Bundle Discount')} icon={Percent}>
        <SelectInput
          label={t('Discount Type')}
          value={config.pricing_settings.discount_type}
          onChange={(v) => updatePricingSettings({ discount_type: v as 'percent' | 'fixed' | 'tiered' })}
          options={[
            { value: 'percent', label: t('Percentage Discount') },
            { value: 'fixed', label: t('Fixed Amount') },
            { value: 'tiered', label: t('Tiered by Amount') },
          ]}
        />

        {config.pricing_settings.discount_type === 'percent' && (
          <NumberInput
            label={t('Discount Percentage')}
            value={config.pricing_settings.discount_percent}
            onChange={(v) => updatePricingSettings({ discount_percent: v || 10 })}
            min={0}
            max={100}
            suffix="%"
            hint={t('Discount percentage on the total bundle')}
          />
        )}

        {config.pricing_settings.discount_type === 'fixed' && (
          <NumberInput
            label={t('Fixed Discount Amount')}
            value={config.pricing_settings.discount_fixed}
            onChange={(v) => updatePricingSettings({ discount_fixed: v || 50 })}
            min={0}
            suffix={currencySymbol}
          />
        )}

        {config.pricing_settings.discount_type === 'tiered' && (
          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 mb-2">{t('Discount Table')}</label>
            <div className="space-y-2 text-sm">
              {config.pricing_settings.discount_tiers.map((tier, idx) => (
                <div key={idx} className="flex items-center gap-2 bg-gray-50 p-2 rounded">
                  <span className="text-gray-500">{t('From')}</span>
                  <input
                    type="number"
                    value={tier.min_amount}
                    onChange={(e) => {
                      const newTiers = [...config.pricing_settings.discount_tiers]
                      newTiers[idx] = { ...tier, min_amount: Number(e.target.value) }
                      updatePricingSettings({ discount_tiers: newTiers })
                    }}
                    className="w-20 px-2 py-1 border rounded"
                  />
                  <span className="text-gray-500">{t('To')}</span>
                  <input
                    type="number"
                    value={tier.max_amount ?? ''}
                    placeholder="∞"
                    onChange={(e) => {
                      const newTiers = [...config.pricing_settings.discount_tiers]
                      newTiers[idx] = { ...tier, max_amount: e.target.value ? Number(e.target.value) : null }
                      updatePricingSettings({ discount_tiers: newTiers })
                    }}
                    className="w-20 px-2 py-1 border rounded"
                  />
                  <span className="text-gray-500">{currencySymbol} →</span>
                  <input
                    type="number"
                    value={tier.discount}
                    onChange={(e) => {
                      const newTiers = [...config.pricing_settings.discount_tiers]
                      newTiers[idx] = { ...tier, discount: Number(e.target.value) }
                      updatePricingSettings({ discount_tiers: newTiers })
                    }}
                    className="w-16 px-2 py-1 border rounded"
                  />
                  <span className="text-gray-500">%</span>
                  <button
                    type="button"
                    onClick={() => {
                      const newTiers = config.pricing_settings.discount_tiers.filter((_, i) => i !== idx)
                      updatePricingSettings({ discount_tiers: newTiers })
                    }}
                    className="p-1 text-red-500 hover:bg-red-50 rounded cursor-pointer"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              ))}
              <button
                type="button"
                onClick={() => {
                  const lastTier = config.pricing_settings.discount_tiers.slice(-1)[0]
                  updatePricingSettings({
                    discount_tiers: [
                      ...config.pricing_settings.discount_tiers,
                      { min_amount: lastTier ? (lastTier.max_amount || 500) : 0, max_amount: null, discount: 15 },
                    ],
                  })
                }}
                className="flex items-center gap-1 text-sm text-purple-600 hover:text-purple-700 cursor-pointer"
              >
                <Plus className="w-4 h-4" />
                {t('Add Tier')}
              </button>
            </div>
          </div>
        )}

        <Toggle
          label={t('Show savings to customer')}
          value={config.pricing_settings.show_savings}
          onChange={(v) => updatePricingSettings({ show_savings: v })}
          hint={t('Show how much the customer saves in the bundle')}
        />
      </Section>

      {/* Coupon Integration */}
      <Section title={t('Auto Coupon')} icon={Tag} badge={config.coupon_settings.enabled ? t('Active') : undefined}>
        <div className="space-y-4">
          {/* Info box explaining what this feature does */}
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
            <p className="text-sm text-blue-800">
              <strong>{t('What is Auto Coupon?')}</strong>
              <br />
              {t('When enabled, the customer will automatically receive a discount coupon with the bundle the bot built. The coupon is applied automatically when the customer adds the bundle to cart.')}
            </p>
          </div>

          <Toggle
            label={t('Enable Auto Coupon')}
            value={config.coupon_settings.enabled}
            onChange={(v) => updateCouponSettings({ enabled: v })}
            hint={config.coupon_settings.enabled ? t('Coupon will be applied automatically to bundles') : t('Click to enable')}
          />

          {config.coupon_settings.enabled && (
            <div className="space-y-3 pt-2 border-t border-gray-100">
              {coupons.length > 0 ? (
                <SelectInput
                  label={t('Select coupon to apply')}
                  value={String(config.coupon_settings.auto_coupon_id || '')}
                  onChange={(v) => updateCouponSettings({ auto_coupon_id: v ? Number(v) : null })}
                  options={[
                    { value: '', label: t('Select coupon...') },
                    ...coupons.map((c) => ({
                      value: String(c.id),
                      label: `${c.code} (${c.amount}${c.discount_type === 'percent' ? '%' : currencySymbol})`,
                    })),
                  ]}
                />
              ) : (
                <div className="bg-amber-50 border border-amber-200 rounded-lg p-3">
                  <p className="text-sm text-amber-800">
                    {t('No coupons available. Create a coupon in WooCommerce to use this feature.')}
                  </p>
                </div>
              )}
              <Toggle
                label={t('Select best coupon automatically')}
                value={config.coupon_settings.auto_select_best}
                onChange={(v) => updateCouponSettings({ auto_select_best: v })}
                hint={t('The system will automatically select the coupon that gives the biggest discount')}
              />
            </div>
          )}
        </div>
      </Section>

      {/* Messages */}
      <Section title={t('Messages')} icon={Settings}>
        <TextInput
          label={t('Success Message')}
          value={config.success_message}
          onChange={(v) => updateConfig({ success_message: v })}
          placeholder={t('Bundle added to cart! 🎉')}
        />
        <TextInput
          label={t('Empty Result Message')}
          value={config.empty_message}
          onChange={(v) => updateConfig({ empty_message: v })}
          placeholder={t('No matching products found')}
        />
      </Section>
    </div>
  )
}

export default BundleBuilderSettings
