import { useState, useEffect, useCallback, useRef } from 'react'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import debounce from 'lodash/debounce'
import { t, sprintf } from '@/lib/i18n'
import { 
    Plus, 
    Edit2, 
    Trash2, 
    FileText, 
    MessageCircle, 
    Calendar,
    Ticket, 
    ShoppingBag,
    Image, 
    Youtube,
    X,
    ChevronDown,
    CheckSquare,
    Square,
    Loader2,
    Gift,
    User,
    ArrowRight,
} from 'lucide-react'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/common/Card'
import { Button } from '@/components/common/Button'
import { ToggleSwitch } from '@/components/common/ToggleSwitch'
import { QuickBotAssign } from '@/components/common/QuickBotAssign'
import { useWidgets } from '@/hooks/useWidgets'
import { widgetsApi } from '@/api/widgets'
import type { CustomWidget, WidgetType } from '@/types/widget'
import { isWidgetFullyConfigured, WIDGET_CONFIG_HINTS } from '@/types/widget'

// Helper to properly parse is_active (can be boolean, number, or string "0"/"1")
const isWidgetActive = (widget: CustomWidget): boolean => {
    const val = widget.is_active
    if (typeof val === 'boolean') return val
    if (typeof val === 'number') return val !== 0
    if (typeof val === 'string') return val !== '0' && val !== ''
    return false
}

function getWidgetTypeConfigAll(): Record<WidgetType, { label: string; icon: typeof FileText; color: string }> {
    return {
        form: { label: t('Dynamic Forms'), icon: FileText, color: 'bg-blue-100 text-blue-700' },
        whatsapp: { label: t('WhatsApp'), icon: MessageCircle, color: 'bg-green-100 text-green-700' },
        calendar_meeting: { label: t('Calendar'), icon: Calendar, color: 'bg-teal-100 text-teal-700' },
        product_card: { label: t('Product Card'), icon: ShoppingBag, color: 'bg-orange-100 text-orange-700' },
        coupon: { label: t('Coupons'), icon: Ticket, color: 'bg-yellow-100 text-yellow-700' },
        gallery: { label: t('Galleries'), icon: Image, color: 'bg-pink-100 text-pink-700' },
        youtube: { label: t('YouTube'), icon: Youtube, color: 'bg-red-100 text-red-700' },
        bundle_builder: { label: t('Bundle Builder'), icon: Gift, color: 'bg-purple-100 text-purple-700' },
        contact_card: { label: t('Contact Cards'), icon: User, color: 'bg-indigo-100 text-indigo-700' },
    }
}

const WOO_MANAGED_TYPES = ['product_card', 'coupon', 'bundle_builder']

export function Widgets() {
    const wooCommerceActive = (window as any).boostbotAdmin?.woocommerce_active ?? false
    
    // All displayable types (includes WooCommerce types for the list view).
    const WIDGET_TYPE_CONFIG = Object.fromEntries(
        Object.entries(getWidgetTypeConfigAll()).filter(([type]) => {
            if (WOO_MANAGED_TYPES.includes(type)) {
                return wooCommerceActive
            }
            return true
        })
    ) as Partial<Record<WidgetType, { label: string; icon: typeof FileText; color: string }>>

    const CREATABLE_TYPE_CONFIG = Object.fromEntries(
        Object.entries(WIDGET_TYPE_CONFIG).filter(([type]) => !WOO_MANAGED_TYPES.includes(type))
    ) as Partial<Record<WidgetType, { label: string; icon: typeof FileText; color: string }>>

    const queryClient = useQueryClient()
    const navigate = useNavigate()
    const [searchParams] = useSearchParams()
    const returnTo = searchParams.get('returnTo')
    const [showCreateMenu, setShowCreateMenu] = useState(false)
    const [selectedWidgets, setSelectedWidgets] = useState<Set<number>>(new Set())
    const [isSelectionMode, setIsSelectionMode] = useState(false)

    // Fetch widgets (filtered by current admin language)
    const { data: widgetsData, isLoading } = useWidgets()

    // Delete widget mutation
    const deleteWidget = useMutation({
        mutationFn: (id: number) => widgetsApi.deleteWidget(id),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['widgets'] })
        },
        onError: () => {
            alert(t('Failed to delete widget. Please try again.'))
        },
    })

    // Bulk delete mutation
    const bulkDeleteWidgets = useMutation({
        mutationFn: (ids: number[]) => widgetsApi.bulkDeleteWidgets(ids),
        onSuccess: (data: Awaited<ReturnType<typeof widgetsApi.bulkDeleteWidgets>>) => {
            queryClient.invalidateQueries({ queryKey: ['widgets'] })
            setSelectedWidgets(new Set())
            setIsSelectionMode(false)
            if (data.data.failed_count > 0) {
                alert(sprintf(t('Deleted %d widgets. %d failed.'), data.data.deleted_count, data.data.failed_count))
            }
        },
        onError: () => {
            alert(t('Failed to delete widgets. Please try again.'))
        },
    })

    const widgets = widgetsData?.data?.widgets || []

    // Group widgets by type
    const widgetsByType = widgets.reduce((acc, widget) => {
        const type = widget.type as WidgetType
        if (!acc[type]) acc[type] = []
        acc[type].push(widget)
        return acc
    }, {} as Record<WidgetType, CustomWidget[]>)

    const handleDeleteWidget = (id: number, name: string) => {
        if (confirm(sprintf(t('Are you sure you want to delete the widget "%s"?'), name))) {
            deleteWidget.mutate(id)
        }
    }

    const toggleWidgetSelection = (id: number) => {
        const newSelection = new Set(selectedWidgets)
        if (newSelection.has(id)) {
            newSelection.delete(id)
        } else {
            newSelection.add(id)
        }
        setSelectedWidgets(newSelection)
    }

    const toggleSelectAllInType = (typeWidgets: CustomWidget[]) => {
        const typeIds = typeWidgets.map(w => w.id)
        const allSelected = typeIds.every(id => selectedWidgets.has(id))
        
        const newSelection = new Set(selectedWidgets)
        if (allSelected) {
            typeIds.forEach(id => newSelection.delete(id))
        } else {
            typeIds.forEach(id => newSelection.add(id))
        }
        setSelectedWidgets(newSelection)
    }

    const handleBulkDelete = () => {
        if (selectedWidgets.size === 0) return
        
        if (confirm(sprintf(t('Are you sure you want to delete %d widgets?'), selectedWidgets.size))) {
            bulkDeleteWidgets.mutate(Array.from(selectedWidgets))
        }
    }

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

    if (isLoading) {
        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>
        )
    }

    return (
        <div className="space-y-6">
            <PageHeader 
                title={t('Widgets')} 
                subtitle={t('Manage interactive widgets for bots - forms, calendars, WhatsApp and more')}
            >
                <div className="flex items-center gap-2">
                    {returnTo && (
                        <Button
                            variant="outline"
                            onClick={() => navigate(returnTo)}
                        >
                            <ArrowRight className="w-4 h-4 me-2" />
                            {t('Back')}
                        </Button>
                    )}
                    {/* Selection Mode Controls */}
                    {isSelectionMode ? (
                        <>
                            <Button
                                variant="outline"
                                onClick={exitSelectionMode}
                            >
                                <X className="w-4 h-4 me-2" />
                                {t('Cancel Selection')}
                            </Button>
                            <Button
                                variant="outline"
                                onClick={handleBulkDelete}
                                disabled={selectedWidgets.size === 0 || bulkDeleteWidgets.isPending}
                                className="text-red-600 hover:bg-red-50 border-red-200"
                            >
                                {bulkDeleteWidgets.isPending ? (
                                    <Loader2 className="w-4 h-4 me-2 animate-spin" />
                                ) : (
                                    <Trash2 className="w-4 h-4 me-2" />
                                )}
                                {t('Delete Selected')} ({selectedWidgets.size})
                            </Button>
                        </>
                    ) : (
                        <>
                            {widgets.length > 0 && (
                                <Button
                                    variant="outline"
                                    onClick={() => setIsSelectionMode(true)}
                                >
                                    <CheckSquare className="w-4 h-4 me-2" />
                                    {t('Select for Deletion')}
                                </Button>
                            )}
                            <div className="relative">
                                <Button onClick={() => setShowCreateMenu(!showCreateMenu)}>
                                    <Plus className="w-4 h-4 me-2" />
                                    {t('Add Widget')}
                                    <ChevronDown className="w-4 h-4 ms-2" />
                                </Button>
                                
                                {/* Create Menu Dropdown */}
                                {showCreateMenu && (
                                    <>
                                        <div 
                                            className="fixed inset-0 z-10" 
                                            onClick={() => setShowCreateMenu(false)} 
                                        />
                                        <div className="absolute end-0 mt-2 w-56 bg-white rounded-lg shadow-lg border border-gray-200 py-2 z-20">
                                            {Object.entries(CREATABLE_TYPE_CONFIG).map(([type, config]) => (
                                                <Link
                                                    key={type}
                                                    to={`/widgets/new?type=${type}`}
                                                    className="flex items-center gap-3 px-4 py-2 hover:bg-gray-50 transition-colors"
                                                    onClick={() => setShowCreateMenu(false)}
                                                >
                                                    <div className={`p-1.5 rounded ${config?.color}`}>
                                                        {config && <config.icon className="w-4 h-4" />}
                                                    </div>
                                                    <span>{config?.label}</span>
                                                </Link>
                                            ))}
                                        </div>
                                    </>
                                )}
                            </div>
                        </>
                    )}
                </div>
            </PageHeader>

            {/* Widgets by Type */}
            {Object.entries(WIDGET_TYPE_CONFIG).map(([type, config]) => {
                const typeWidgets = widgetsByType[type as WidgetType] || []
                const Icon = config?.icon
                const allSelectedInType = typeWidgets.length > 0 && typeWidgets.every(w => selectedWidgets.has(w.id))
                const someSelectedInType = typeWidgets.some(w => selectedWidgets.has(w.id))

                if (!config) return null

                return (
                    <Card key={type}>
                        <CardHeader>
                            <CardTitle className="flex items-center gap-2">
                                {/* Select All Checkbox for this type */}
                                {isSelectionMode && typeWidgets.length > 0 && (
                                    <button
                                        onClick={() => toggleSelectAllInType(typeWidgets)}
                                        className="p-1 hover:bg-gray-100 rounded transition-colors"
                                        title={allSelectedInType ? t('Deselect All') : t('Select All')}
                                    >
                                        {allSelectedInType ? (
                                            <CheckSquare className="w-5 h-5 text-primary-600" />
                                        ) : someSelectedInType ? (
                                            <CheckSquare className="w-5 h-5 text-primary-400" />
                                        ) : (
                                            <Square className="w-5 h-5 text-gray-400" />
                                        )}
                                    </button>
                                )}
                                <div className={`p-2 rounded-lg ${config.color}`}>
                                    <Icon className="w-5 h-5" />
                                </div>
                                {config.label}
                                <span className="text-sm font-normal text-gray-500">
                                    ({typeWidgets.length})
                                </span>
                            </CardTitle>
                        </CardHeader>
                        <CardContent>
                            {typeWidgets.length > 0 ? (
                                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                    {typeWidgets.map((widget) => (
                                        <WidgetCard
                                            key={widget.id}
                                            widget={widget}
                                            config={config}
                                            onDelete={() => handleDeleteWidget(widget.id, widget.name)}
                                            isSelectionMode={isSelectionMode}
                                            isSelected={selectedWidgets.has(widget.id)}
                                            onToggleSelect={() => toggleWidgetSelection(widget.id)}
                                            returnTo={returnTo}
                                        />
                                    ))}
                                </div>
                            ) : (
                                <div className="text-center py-8 text-gray-500">
                                    <Icon className="w-10 h-10 mx-auto mb-2 opacity-30" />
                                    <p className="mb-3">{t('No widgets of this type defined')}</p>
                                    <Link to={`/widgets/new?type=${type}`}>
                                        <Button variant="outline" size="sm">
                                            <Plus className="w-4 h-4 me-1" />
                                            {t('Add')}
                                        </Button>
                                    </Link>
                                </div>
                            )}
                        </CardContent>
                    </Card>
                )
            })}

            {/* Empty State */}
            {widgets.length === 0 && (
                <Card>
                    <CardContent className="text-center py-12">
                        <FileText className="w-16 h-16 mx-auto mb-4 text-gray-300" />
                        <h3 className="text-lg font-medium text-gray-900 mb-2">
                            {t('No widgets yet')}
                        </h3>
                        <p className="text-gray-500 mb-4">
                            {t('Create interactive widgets like forms, calendars, and WhatsApp buttons')}
                        </p>
                        <Button onClick={() => setShowCreateMenu(true)}>
                            <Plus className="w-4 h-4 me-2" />
                            {t('Create First Widget')}
                        </Button>
                    </CardContent>
                </Card>
            )}
        </div>
    )
}

interface WidgetCardProps {
    widget: CustomWidget
    config: { label: string; icon: typeof FileText; color: string }
    onDelete: () => void
    isSelectionMode?: boolean
    isSelected?: boolean
    onToggleSelect?: () => void
    returnTo?: string | null
}

function WidgetCard({ widget, config, onDelete, isSelectionMode, isSelected, onToggleSelect, returnTo }: WidgetCardProps) {
    const Icon = config.icon
    const queryClient = useQueryClient()
    const fullyConfigured = isWidgetFullyConfigured(widget)
    const [showConfigHint, setShowConfigHint] = useState(false)
    const hintTimeoutRef = useRef<ReturnType<typeof setTimeout>>()
    
    // Local state for the toggle - instant UI updates
    const [isActive, setIsActive] = useState(() => isWidgetActive(widget))
    
    // If not fully configured, force toggle off
    useEffect(() => {
        if (!fullyConfigured && isActive) {
            setIsActive(false)
        }
    }, [fullyConfigured])
    
    // Sync local state when widget prop changes (e.g., after query refetch)
    useEffect(() => {
        setIsActive(isWidgetActive(widget))
    }, [widget.is_active])
    
    // Mutation for saving to server
    const updateMutation = useMutation({
        mutationFn: (newIsActive: boolean) => 
            widgetsApi.updateWidget(widget.id, { is_active: newIsActive }),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['widgets'] })
        },
        onError: () => {
            // Revert to server state on error
            setIsActive(isWidgetActive(widget))
        },
    })
    
    // Debounced save function - stable reference using useRef + useCallback
    const debouncedSaveRef = useRef<ReturnType<typeof debounce>>()
    
    // Create/update debounced function
    const debouncedSave = useCallback((newValue: boolean) => {
        // Cancel any pending debounced call
        if (debouncedSaveRef.current) {
            debouncedSaveRef.current.cancel()
        }
        
        // Create new debounced function and call it immediately
        debouncedSaveRef.current = debounce((value: boolean) => {
            updateMutation.mutate(value)
        }, 500)
        
        debouncedSaveRef.current(newValue)
    }, [updateMutation])
    
    // Cleanup on unmount
    useEffect(() => {
        return () => {
            if (debouncedSaveRef.current) {
                debouncedSaveRef.current.cancel()
            }
            if (hintTimeoutRef.current) {
                clearTimeout(hintTimeoutRef.current)
            }
        }
    }, [])
    
    const handleToggle = useCallback(() => {
        // If not fully configured, show hint and block toggle
        if (!fullyConfigured) {
            setShowConfigHint(true)
            if (hintTimeoutRef.current) clearTimeout(hintTimeoutRef.current)
            hintTimeoutRef.current = setTimeout(() => setShowConfigHint(false), 3000)
            return
        }
        const newValue = !isActive
        setIsActive(newValue)      // Instant UI update
        debouncedSave(newValue)    // Debounced API call
    }, [isActive, debouncedSave, fullyConfigured])

    return (
        <div 
            className={`bg-gray-50 rounded-lg p-4 transition-colors ${
                isSelectionMode 
                    ? 'cursor-pointer hover:bg-gray-100' 
                    : 'hover:bg-gray-100'
            } ${isSelected ? 'ring-2 ring-primary-500 bg-primary-50' : ''} ${!isActive ? 'opacity-60' : ''}`}
            onClick={isSelectionMode ? onToggleSelect : undefined}
        >
            <div className="flex items-start gap-3">
                {/* Selection Checkbox */}
                {isSelectionMode && (
                    <button
                        onClick={(e) => {
                            e.stopPropagation()
                            onToggleSelect?.()
                        }}
                        className="mt-1 p-0.5"
                    >
                        {isSelected ? (
                            <CheckSquare className="w-5 h-5 text-primary-600" />
                        ) : (
                            <Square className="w-5 h-5 text-gray-400" />
                        )}
                    </button>
                )}
                <div className={`p-2 rounded-lg ${config.color} ${!isActive ? 'opacity-50' : ''}`}>
                    <Icon className="w-5 h-5" />
                </div>
                <div className="flex-1 min-w-0">
                    <h4 className="font-medium text-gray-900 truncate">
                        {widget.name}
                    </h4>
                    <div className="flex items-center gap-2 mt-1 text-sm">
                        {!!(widget.is_system_managed) && (
                            <span className="text-xs text-purple-600 bg-purple-50 px-1.5 py-0.5 rounded">
                                {t('Managed by WooCommerce')}
                            </span>
                        )}
                        {widget.type === 'form' && widget.field_count !== undefined && (
                            <span className="text-gray-500">
                                {widget.field_count} {t('fields')}
                            </span>
                        )}
                        {widget.usage_count !== undefined && widget.usage_count > 0 && (
                            <span className="text-gray-500">
                                • {widget.usage_count} {t('uses')}
                            </span>
                        )}
                    </div>
                    {/* Not fully configured warning */}
                    {!fullyConfigured && (
                        <p className="text-xs text-amber-600 mt-1">
                            ⚠ {t('Not fully configured')}
                        </p>
                    )}
                </div>
                {/* Toggle switch - instant local state UI */}
                {!isSelectionMode && (
                    <div 
                        className="relative" 
                        onClick={(e) => e.stopPropagation()}
                        onMouseEnter={() => {
                            if (!fullyConfigured) {
                                setShowConfigHint(true)
                                if (hintTimeoutRef.current) clearTimeout(hintTimeoutRef.current)
                            }
                        }}
                        onMouseLeave={() => {
                            if (!fullyConfigured) {
                                hintTimeoutRef.current = setTimeout(() => setShowConfigHint(false), 300)
                            }
                        }}
                    >
                        <ToggleSwitch
                            checked={isActive}
                            onChange={handleToggle}
                            disabled={!fullyConfigured}
                            size="md"
                            ariaLabel={!fullyConfigured ? t('Cannot activate - configuration missing') : isActive ? t('Deactivate widget') : t('Activate widget')}
                        />
                        {/* Configuration hint tooltip */}
                        {showConfigHint && !fullyConfigured && (
                            <div className="absolute end-0 top-full mt-1 z-30 w-48 bg-gray-800 text-white text-xs rounded-lg px-3 py-2 shadow-lg pointer-events-none">
                                {t(WIDGET_CONFIG_HINTS[widget.type as WidgetType] || 'Widget configuration must be completed')}
                            </div>
                        )}
                    </div>
                )}
            </div>
            
            {/* Hide action buttons in selection mode */}
            {!isSelectionMode && (
                <div className="flex gap-2 mt-3">
                    <Link to={`/widgets/${widget.id}${returnTo ? `?returnTo=${encodeURIComponent(returnTo)}` : ''}`} className="flex-1">
                        <Button variant="outline" size="sm" className="w-full">
                            <Edit2 className="w-4 h-4 me-1" />
                            {t('Edit')}
                        </Button>
                    </Link>
                    <QuickBotAssign
                        entityType="widget"
                        entityId={widget.id}
                        initialCount={widget.linked_bots_count}
                    />
                    {!widget.is_system_managed ? (
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={onDelete}
                            className="text-red-600 hover:bg-red-50"
                        >
                            <Trash2 className="w-4 h-4" />
                        </Button>
                    ) : (
                        <Button
                            variant="outline"
                            size="sm"
                            disabled
                            className="text-gray-400 cursor-not-allowed"
                            title={t('This widget is managed by a WooCommerce Preset')}
                        >
                            <Trash2 className="w-4 h-4" />
                        </Button>
                    )}
                </div>
            )}
        </div>
    )
}
