/**
 * WooCommerce Settings Page - Presets & Coupons Management
 * @since 1.3.0 (Week 25)
 */

import { useState } from 'react'
import { Link } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { 
    Plus, 
    Edit2, 
    Trash2, 
    Star, 
    Package, 
    Tag, 
    CheckSquare, 
    Square, 
    X, 
    ShoppingCart,
    Copy,
    BarChart3,
    AlertCircle,
    TrendingUp,
    Zap,
    Percent,
    Info
} from 'lucide-react'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardContent } from '@/components/common/Card'
import { StatCard } from '@/components/dashboard/StatCard'
import { apiClient } from '@/api/client'
import { useLanguage } from '@/contexts/LanguageContext'
import { useWooCommerceStats } from '@/hooks/useWooCommerceStats'
import { sprintf, t } from '@/lib/i18n'
import type { StatsPeriod } from '@/api/woocommerce'

interface WooCommercePreset {
    id: number
    name: string
    slug: string
    description: string | null
    bundle_enabled: number
    bundle_min_products: number
    bundle_max_products: number
    bundle_discount_type: string
    bundle_discount_value: number
    coupon_enabled: number
    coupon_auto_apply: number
    coupon_max_per_order: number
    product_mode: string
    is_default: number
    is_system: number
    is_active: number
    coupon_count?: number
    bot_count?: number
    created_at: string
    updated_at: string
}

function getCurrencySymbol(): string {
    const cfg = (window as any).boostbotAdmin
    return cfg?.woocommerce_currency_symbol || '₪'
}

export function WooCommerceSettings() {
    const queryClient = useQueryClient()
    const { currentLanguage } = useLanguage()
    const [activeTab, setActiveTab] = useState<'presets' | 'statistics'>('presets')
    const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set())
    const [isSelectionMode, setIsSelectionMode] = useState(false)

    // Check WooCommerce status
    const { data: statusData, isLoading: isStatusLoading } = useQuery({
        queryKey: ['woocommerce-status'],
        queryFn: () => apiClient.get<{ data: { active: boolean; products: number; categories: number } }>('woocommerce/status'),
    })

    // Fetch presets (filtered by current admin language)
    const { data: presetsData, isLoading: isPresetsLoading } = useQuery({
        queryKey: ['woocommerce-presets', currentLanguage],
        queryFn: () => apiClient.get<{ data: { presets: WooCommercePreset[] } }>('woocommerce/presets', { language: currentLanguage }),
        enabled: statusData?.data?.active,
    })

    const deletePreset = useMutation({
        mutationFn: (id: number) => apiClient.delete(`woocommerce/presets/${id}`),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['woocommerce-presets'] })
        },
        onError: (error: any) => {
            console.error('Failed to delete preset:', error)
            alert(error?.message || t('Error deleting preset'))
        },
    })

    const duplicatePreset = useMutation({
        mutationFn: (id: number) => apiClient.post(`woocommerce/presets/${id}/duplicate`, {}),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['woocommerce-presets'] })
        },
        onError: (error: any) => {
            console.error('Failed to duplicate preset:', error)
            alert(error?.message || t('Error duplicating preset'))
        },
    })

    const presets = presetsData?.data?.presets || []
    const wooCommerceActive = statusData?.data?.active || false

    const handleDelete = (id: number, name: string, isSystem: boolean) => {
        if (isSystem) {
            alert(t('System presets cannot be deleted'))
            return
        }
        if (confirm(sprintf(t('Are you sure you want to delete "%s"?'), name))) {
            deletePreset.mutate(id)
        }
    }

    const handleDuplicate = (id: number) => {
        duplicatePreset.mutate(id)
    }

    const handleToggleSelection = (id: number) => {
        const newSelected = new Set(selectedIds)
        if (newSelected.has(id)) {
            newSelected.delete(id)
        } else {
            newSelected.add(id)
        }
        setSelectedIds(newSelected)
    }

    const exitSelectionMode = () => {
        setIsSelectionMode(false)
        setSelectedIds(new Set())
    }

    if (isStatusLoading) {
        return (
            <div className="flex items-center justify-center min-h-[400px]">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600" />
            </div>
        )
    }

    if (!wooCommerceActive) {
        return (
            <div className="space-y-6 animate-fade-in">
                <PageHeader
                    title={t('WooCommerce Settings')}
                    subtitle={t('Manage bundles and coupons')}
                />
                <Card>
                    <CardContent className="py-16 text-center">
                        <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-yellow-100 flex items-center justify-center">
                            <AlertCircle className="w-8 h-8 text-yellow-600" />
                        </div>
                        <h3 className="text-lg font-medium text-gray-900 mb-2">
                            {t('WooCommerce is inactive')}
                        </h3>
                        <p className="text-gray-500 max-w-md mx-auto">
                            {t('To use WooCommerce settings, install and activate the WooCommerce plugin on your site.')}
                        </p>
                    </CardContent>
                </Card>
            </div>
        )
    }

    return (
        <div className="space-y-6 animate-fade-in">
            <PageHeader
                title={t('WooCommerce Settings')}
                subtitle={t('Manage bundle and coupon presets')}
            >
                <div className="flex items-center gap-2">
                    {!isSelectionMode ? (
                        <>
                            <Link
                                to="/woocommerce-presets/new"
                                className="flex items-center gap-2 px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors"
                            >
                                <Plus className="w-4 h-4" />
                                {t('New Preset')}
                            </Link>
                        </>
                    ) : (
                        <>
                            <span className="text-sm text-gray-600">
                                {sprintf(t('%d selected'), selectedIds.size)}
                            </span>
                            <button
                                onClick={exitSelectionMode}
                                className="flex items-center gap-2 px-3 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                            >
                                <X className="w-4 h-4" />
                            </button>
                        </>
                    )}
                </div>
            </PageHeader>

            {/* Status Bar */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <Card className="bg-gradient-to-br from-purple-50 to-white">
                    <CardContent className="flex items-center gap-4 py-4">
                        <div className="w-12 h-12 rounded-full bg-purple-100 flex items-center justify-center">
                            <Package className="w-6 h-6 text-purple-600" />
                        </div>
                        <div>
                            <p className="text-2xl font-bold text-gray-900">{presets.length}</p>
                            <p className="text-sm text-gray-500">{t('Presets')}</p>
                        </div>
                    </CardContent>
                </Card>

                <Card className="bg-gradient-to-br from-green-50 to-white">
                    <CardContent className="flex items-center gap-4 py-4">
                        <div className="w-12 h-12 rounded-full bg-green-100 flex items-center justify-center">
                            <ShoppingCart className="w-6 h-6 text-green-600" />
                        </div>
                        <div>
                            <p className="text-2xl font-bold text-gray-900">{statusData?.data?.products || 0}</p>
                            <p className="text-sm text-gray-500">{t('Products')}</p>
                        </div>
                    </CardContent>
                </Card>

                <Card className="bg-gradient-to-br from-blue-50 to-white">
                    <CardContent className="flex items-center gap-4 py-4">
                        <div className="w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center">
                            <Tag className="w-6 h-6 text-blue-600" />
                        </div>
                        <div>
                            <p className="text-2xl font-bold text-gray-900">{statusData?.data?.categories || 0}</p>
                            <p className="text-sm text-gray-500">{t('Categories')}</p>
                        </div>
                    </CardContent>
                </Card>
            </div>

            {/* Tabs */}
            <div className="border-b border-gray-200">
                <nav className="flex gap-8" aria-label="Tabs">
                    <button
                        onClick={() => setActiveTab('presets')}
                        className={`py-4 px-1 border-b-2 font-medium text-sm transition-colors ${
                            activeTab === 'presets'
                                ? 'border-primary-600 text-primary-600'
                                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                        }`}
                    >
                        <span className="flex items-center gap-2">
                            <Package className="w-4 h-4" />
                            {t('Presets')}
                        </span>
                    </button>
                    <button
                        onClick={() => setActiveTab('statistics')}
                        className={`py-4 px-1 border-b-2 font-medium text-sm transition-colors ${
                            activeTab === 'statistics'
                                ? 'border-primary-600 text-primary-600'
                                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                        }`}
                    >
                        <span className="flex items-center gap-2">
                            <BarChart3 className="w-4 h-4" />
                            {t('Statistics')}
                        </span>
                    </button>
                </nav>
            </div>

            {/* Content */}
            {activeTab === 'presets' && (
                <>
                    {isPresetsLoading ? (
                        <div className="flex items-center justify-center min-h-[200px]">
                            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600" />
                        </div>
                    ) : presets.length === 0 ? (
                        <Card>
                            <CardContent className="py-16 text-center">
                                <Package className="w-16 h-16 mx-auto text-gray-300 mb-4" />
                                <h3 className="text-lg font-medium text-gray-900 mb-2">
                                    {t('No presets yet')}
                                </h3>
                                <p className="text-gray-500 mb-6">
                                    {t('Create your first preset to start configuring bundles and coupons')}
                                </p>
                                <Link
                                    to="/woocommerce-presets/new"
                                    className="inline-flex items-center gap-2 px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors"
                                >
                                    <Plus className="w-4 h-4" />
                                    {t('Create Preset')}
                                </Link>
                            </CardContent>
                        </Card>
                    ) : (
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                            {presets.map((preset) => (
                                <PresetCard
                                    key={preset.id}
                                    preset={preset}
                                    onDelete={() => handleDelete(preset.id, preset.name, Number(preset.is_system) === 1)}
                                    onDuplicate={() => handleDuplicate(preset.id)}
                                    isSelectionMode={isSelectionMode}
                                    isSelected={selectedIds.has(preset.id)}
                                    onToggleSelection={() => handleToggleSelection(preset.id)}
                                />
                            ))}
                        </div>
                    )}
                </>
            )}

            {activeTab === 'statistics' && (
                <WooCommerceStatisticsTab language={currentLanguage} />
            )}
        </div>
    )
}

interface PresetCardProps {
    preset: WooCommercePreset
    onDelete: () => void
    onDuplicate: () => void
    isSelectionMode?: boolean
    isSelected?: boolean
    onToggleSelection?: () => void
}

function PresetCard({ preset, onDelete, onDuplicate, isSelectionMode, isSelected, onToggleSelection }: PresetCardProps) {
    const currencySymbol = getCurrencySymbol()
    const canSelect = Number(preset.is_system) !== 1

    return (
        <Card className={`relative group hover:shadow-xl transition-all duration-300 overflow-hidden ${isSelected ? 'ring-2 ring-primary-500' : ''}`}>
            {/* Selection Checkbox */}
            {isSelectionMode && canSelect && (
                <button
                    onClick={onToggleSelection}
                    className="absolute top-3 left-3 z-10 w-6 h-6 flex items-center justify-center rounded bg-white shadow-md hover:bg-gray-50 transition-colors"
                >
                    {isSelected ? (
                        <CheckSquare className="w-5 h-5 text-primary-600" />
                    ) : (
                        <Square className="w-5 h-5 text-gray-400" />
                    )}
                </button>
            )}

            {/* Header */}
            <div className="px-4 py-3 border-b border-gray-100 bg-gradient-to-l from-purple-50 to-white">
                <div className="flex flex-col gap-1">
                    <h3 className="font-semibold text-gray-900 text-base">
                        {preset.name}
                    </h3>
                    <div className="flex items-center gap-2 flex-wrap">
                        {Number(preset.is_default) === 1 && (
                            <div className="flex items-center gap-1 px-2 py-1 bg-yellow-100 text-yellow-700 text-xs font-medium rounded-full">
                                <Star className="w-3 h-3 fill-yellow-500" />
                                {t('Default')}
                            </div>
                        )}
                        {Number(preset.is_system) === 1 && (
                            <span className="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full">
                                {t('System')}
                            </span>
                        )}
                    </div>
                </div>
            </div>

            {/* Content */}
            <CardContent className="pt-4 pb-4">
                {/* Description */}
                {preset.description && (
                    <p className="text-sm text-gray-500 line-clamp-2 mb-4">
                        {preset.description}
                    </p>
                )}

                {/* Feature Badges */}
                <div className="flex flex-wrap gap-2 mb-4">
                    {Number(preset.bundle_enabled) === 1 && (
                        <span className="inline-flex items-center gap-1 px-2 py-1 bg-purple-100 text-purple-700 text-xs rounded-full">
                            <Package className="w-3 h-3" />
                            {t('Bundles')}
                        </span>
                    )}
                    {Number(preset.coupon_enabled) === 1 && (
                        <span className="inline-flex items-center gap-1 px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full">
                            <Tag className="w-3 h-3" />
                            {t('Coupons')}
                        </span>
                    )}
                    {!Number(preset.is_active) && (
                        <span className="inline-flex items-center gap-1 px-2 py-1 bg-gray-100 text-gray-500 text-xs rounded-full">
                            {t('Inactive')}
                        </span>
                    )}
                </div>

                {/* Stats */}
                <div className="grid grid-cols-2 gap-3 mb-4">
                    <div className="text-center p-2 bg-gray-50 rounded-lg">
                        <p className="text-lg font-bold text-gray-900">{preset.coupon_count || 0}</p>
                        <p className="text-xs text-gray-500">{t('Coupons')}</p>
                    </div>
                    <div className="text-center p-2 bg-gray-50 rounded-lg">
                        <p className="text-lg font-bold text-gray-900">{preset.bot_count || 0}</p>
                        <p className="text-xs text-gray-500">{t('Bots')}</p>
                    </div>
                </div>

                {/* Discount Info */}
                {Number(preset.bundle_enabled) === 1 && preset.bundle_discount_value > 0 && (
                    <div className="mb-4 p-2 bg-green-50 rounded-lg text-center">
                        <p className="text-sm font-medium text-green-700">
                            {t('Discount')}: {preset.bundle_discount_value}
                            {preset.bundle_discount_type === 'percent' ? '%' : currencySymbol}
                        </p>
                    </div>
                )}

                {/* Actions */}
                <div className="flex gap-2">
                    <Link
                        to={`/woocommerce-presets/${preset.id}`}
                        className="flex-1 flex items-center justify-center gap-1 px-3 py-2 text-sm border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                    >
                        <Edit2 className="w-4 h-4" />
                        {t('Edit')}
                    </Link>

                    <button
                        onClick={onDuplicate}
                        className="px-3 py-2 text-sm border border-gray-300 rounded-lg hover:bg-blue-50 hover:border-blue-300 transition-colors"
                        title={t('Duplicate')}
                    >
                        <Copy className="w-4 h-4" />
                    </button>

                    {Number(preset.is_system) !== 1 && (
                        <button
                            onClick={onDelete}
                            className="px-3 py-2 text-sm border border-gray-300 rounded-lg text-red-600 hover:bg-red-50 hover:border-red-300 transition-colors"
                            title={t('Delete')}
                        >
                            <Trash2 className="w-4 h-4" />
                        </button>
                    )}
                </div>
            </CardContent>
        </Card>
    )
}

const PERIOD_OPTIONS: { value: StatsPeriod; label: string }[] = [
    { value: '7d', label: 'Last 7 days' },
    { value: '30d', label: 'Last 30 days' },
    { value: '90d', label: 'Last 90 days' },
    { value: 'all', label: 'All Time' },
]

const WIDGET_TYPE_LABELS: Record<string, string> = {
    bundle_builder: 'Bundle Builder',
    coupon: 'Coupon',
    product_card: 'Product Card',
}

function WooCommerceStatisticsTab({ language }: { language: string }) {
    const currencySymbol = getCurrencySymbol()
    const [period, setPeriod] = useState<StatsPeriod>('30d')
    const { data, isLoading } = useWooCommerceStats(language, period)

    const stats = data?.data

    if (isLoading) {
        return (
            <div className="flex items-center justify-center min-h-[300px]">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600" />
            </div>
        )
    }

    const bundles = stats?.bundles ?? { total: 0, suggested: 0, accepted: 0, conversion_rate: 0, avg_discount: 0, period_total: 0, period_accepted: 0 }
    const triggers = stats?.widget_triggers ?? { bundle_builder: 0, coupon: 0, product_card: 0 }
    const topProducts = stats?.top_products ?? []
    const wcAttr = stats?.wc_attribution ?? { coupon_orders: 0, coupon_revenue: 0, available: false }
    const totalTriggers = triggers.bundle_builder + triggers.coupon + triggers.product_card

    return (
        <div className="space-y-6">
            {/* Row 1: Summary cards */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                <StatCard
                    title={t('Total Bundles')}
                    value={bundles.total}
                    icon={Package}
                    color="primary"
                />
                <StatCard
                    title={t('Conversion Rate')}
                    value={`${bundles.conversion_rate}%`}
                    icon={TrendingUp}
                    color="success"
                />
                <StatCard
                    title={t('Widget Triggers')}
                    value={totalTriggers}
                    icon={Zap}
                    color="warning"
                />
                <StatCard
                    title={t('Average Discount')}
                    value={bundles.avg_discount > 0 ? `${currencySymbol}${bundles.avg_discount}` : '—'}
                    icon={Percent}
                    color="accent"
                />
            </div>

            {/* Row 2: Period selector + bundle breakdown */}
            <Card>
                <CardContent className="py-5">
                    <div className="flex items-center justify-between mb-5">
                        <h3 className="text-base font-semibold text-gray-900">{t('Bundles by Period')}</h3>
                        <div className="flex gap-1 bg-gray-100 rounded-lg p-1">
                            {PERIOD_OPTIONS.map(opt => (
                                <button
                                    key={opt.value}
                                    onClick={() => setPeriod(opt.value)}
                                    className={`px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${
                                        period === opt.value
                                            ? 'bg-white text-primary-700 shadow-sm'
                                            : 'text-gray-500 hover:text-gray-700'
                                    }`}
                                >
                                    {t(opt.label)}
                                </button>
                            ))}
                        </div>
                    </div>

                    {bundles.period_total === 0 ? (
                        <p className="text-sm text-gray-400 text-center py-6">{t('No data yet')}</p>
                    ) : (
                        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                            <PeriodMetric label={t('Suggested')} value={bundles.period_total - bundles.period_accepted} />
                            <PeriodMetric label={t('Accepted')} value={bundles.period_accepted} />
                            <PeriodMetric
                                label={t('Conversion Rate')}
                                value={bundles.period_total > 0
                                    ? `${Math.round((bundles.period_accepted / bundles.period_total) * 100)}%`
                                    : '0%'}
                            />
                            <PeriodMetric label={t('Total')} value={bundles.period_total} />
                        </div>
                    )}
                </CardContent>
            </Card>

            {/* Row 3: Top products + Widget usage */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {/* Top products */}
                <Card>
                    <CardContent className="py-5">
                        <h3 className="text-base font-semibold text-gray-900 mb-4">{t('Top Products in Bundles')}</h3>
                        {topProducts.length === 0 ? (
                            <p className="text-sm text-gray-400 text-center py-4">{t('No data yet')}</p>
                        ) : (
                            <ul className="space-y-3">
                                {topProducts.map((p, i) => (
                                    <li key={p.product_id} className="flex items-center justify-between">
                                        <div className="flex items-center gap-3">
                                            <span className="flex-shrink-0 w-6 h-6 rounded-full bg-primary-100 text-primary-700 text-xs font-bold flex items-center justify-center">
                                                {i + 1}
                                            </span>
                                            <span className="text-sm text-gray-700 truncate max-w-[200px]">{p.product_name}</span>
                                        </div>
                                        <span className="text-sm font-medium text-gray-500">
                                            {p.appearances} {t('appearances')}
                                        </span>
                                    </li>
                                ))}
                            </ul>
                        )}
                    </CardContent>
                </Card>

                {/* Widget usage */}
                <Card>
                    <CardContent className="py-5">
                        <h3 className="text-base font-semibold text-gray-900 mb-4">{t('Widget Usage')}</h3>
                        {totalTriggers === 0 ? (
                            <p className="text-sm text-gray-400 text-center py-4">{t('No data yet')}</p>
                        ) : (
                            <div className="space-y-4">
                                {Object.entries(triggers).map(([type, count]) => {
                                    const pct = totalTriggers > 0 ? Math.round((count / totalTriggers) * 100) : 0
                                    return (
                                        <div key={type}>
                                            <div className="flex items-center justify-between mb-1">
                                                <span className="text-sm text-gray-700">
                                                    {t(WIDGET_TYPE_LABELS[type] ?? type)}
                                                </span>
                                                <span className="text-sm font-medium text-gray-900">{count}</span>
                                            </div>
                                            <div className="w-full bg-gray-100 rounded-full h-2">
                                                <div
                                                    className="bg-primary-500 h-2 rounded-full transition-all"
                                                    style={{ width: `${pct}%` }}
                                                />
                                            </div>
                                        </div>
                                    )
                                })}
                            </div>
                        )}
                    </CardContent>
                </Card>
            </div>

            {/* Row 4: WooCommerce attribution */}
            {wcAttr.available ? (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <StatCard
                        title={t('Orders via Coupons')}
                        value={wcAttr.coupon_orders}
                        icon={ShoppingCart}
                        color="success"
                    />
                    <StatCard
                        title={t('Revenue via Coupons')}
                        value={`${currencySymbol}${wcAttr.coupon_revenue.toLocaleString()}`}
                        icon={TrendingUp}
                        color="success"
                    />
                </div>
            ) : (
                <Card>
                    <CardContent className="py-4">
                        <div className="flex items-center gap-3 text-sm text-gray-500">
                            <Info className="w-4 h-4 text-gray-400 flex-shrink-0" />
                            <span>{t('Revenue attribution will be available once orders are placed using BoostBot coupons')}</span>
                        </div>
                    </CardContent>
                </Card>
            )}
        </div>
    )
}

function PeriodMetric({ label, value }: { label: string; value: string | number }) {
    return (
        <div className="text-center p-3 bg-gray-50 rounded-lg">
            <p className="text-xl font-bold text-gray-900">{value}</p>
            <p className="text-xs text-gray-500 mt-1">{label}</p>
        </div>
    )
}

