/**
 * QuickBotAssign Component
 * A compact dropdown for quickly assigning/unassigning bots from preset cards
 * Used on listing pages (Opening Screen Presets, Appearance Presets, Widgets)
 */
import { useState, useRef, useEffect } from 'react'
import { t } from '@/lib/i18n'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Bot, Check, Loader2 } from 'lucide-react'
import { apiClient } from '@/api/client'

interface QuickBotAssignProps {
    entityType: 'opening-screen-preset' | 'appearance-preset' | 'widget'
    entityId: number
    /** Pre-loaded count of linked bots (shown before dropdown is opened). */
    initialCount?: number
}

interface LinkedBot {
    id: number
    bot_name: string
}

interface AllBot {
    id: number
    bot_name: string
}

// Map entity types to their API endpoint plurals
const ENTITY_API_MAP: Record<string, string> = {
    'opening-screen-preset': 'opening-screen-presets',
    'appearance-preset': 'appearance-presets',
    'widget': 'widgets',
}

export function QuickBotAssign({ entityType, entityId, initialCount }: QuickBotAssignProps) {
    const queryClient = useQueryClient()
    const [isOpen, setIsOpen] = useState(false)
    const dropdownRef = useRef<HTMLDivElement>(null)
    const apiEndpoint = ENTITY_API_MAP[entityType]

    // Close dropdown on click outside
    useEffect(() => {
        function handleClickOutside(event: MouseEvent) {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setIsOpen(false)
            }
        }
        if (isOpen) {
            document.addEventListener('mousedown', handleClickOutside)
            return () => document.removeEventListener('mousedown', handleClickOutside)
        }
    }, [isOpen])

    // Fetch linked bots for this entity
    const { data: linkedData } = useQuery({
        queryKey: [entityType, entityId, 'linked-bots'],
        queryFn: () => apiClient.get<{ data: { bots: LinkedBot[] } }>(`${apiEndpoint}/${entityId}/linked-bots`),
        enabled: isOpen,
    })

    // Fetch all bots
    const { data: allBotsData } = useQuery({
        queryKey: ['bots', 1, 50],
        queryFn: () => apiClient.get<{ data: { bots: AllBot[] } }>('bots', { per_page: 50 }),
        enabled: isOpen,
    })

    // Link mutation
    const linkMutation = useMutation({
        mutationFn: (botId: number) =>
            apiClient.post(`${apiEndpoint}/${entityId}/link-bot/${botId}`),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: [entityType, entityId, 'linked-bots'] })
            queryClient.invalidateQueries({ queryKey: ['bots'] })
        },
    })

    // Unlink mutation
    const unlinkMutation = useMutation({
        mutationFn: (botId: number) =>
            apiClient.post(`${apiEndpoint}/${entityId}/unlink-bot/${botId}`),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: [entityType, entityId, 'linked-bots'] })
            queryClient.invalidateQueries({ queryKey: ['bots'] })
        },
    })

    const linkedBots = linkedData?.data?.bots || []
    const allBots = allBotsData?.data?.bots || []
    const linkedBotIds = new Set(linkedBots.map(b => b.id))
    const isLoading = !linkedData || !allBotsData
    const isMutating = linkMutation.isPending || unlinkMutation.isPending

    // Use server-provided count before dropdown is first opened, then live count
    const displayCount = linkedData ? linkedBots.length : (initialCount ?? 0)

    const handleToggleBot = (botId: number) => {
        if (isMutating) return
        if (linkedBotIds.has(botId)) {
            unlinkMutation.mutate(botId)
        } else {
            linkMutation.mutate(botId)
        }
    }

    return (
        <div className="relative" ref={dropdownRef}>
            <button
                onClick={(e) => {
                    e.preventDefault()
                    e.stopPropagation()
                    setIsOpen(!isOpen)
                }}
                className={`flex items-center gap-1 px-3 py-1.5 rounded-lg transition-colors text-sm ${
                    displayCount > 0
                        ? 'bg-primary-50 text-primary-600 hover:bg-primary-100'
                        : 'bg-gray-50 text-gray-600 hover:bg-gray-100'
                }`}
                title={t('Assign to bots')}
            >
                <Bot className="w-3.5 h-3.5" />
                {displayCount > 0 && (
                    <span className="text-xs font-medium">{displayCount}</span>
                )}
            </button>

            {isOpen && (
                <div 
                    className="absolute end-0 mt-1 w-56 bg-white rounded-lg shadow-xl border border-gray-200 z-50 overflow-hidden"
                    onClick={(e) => e.stopPropagation()}
                >
                    <div className="px-3 py-2 bg-gray-50 border-b border-gray-100">
                        <span className="text-xs font-medium text-gray-500">{t('Assign to bots')}</span>
                    </div>
                    
                    <div className="max-h-52 overflow-y-auto">
                        {isLoading ? (
                            <div className="flex items-center justify-center py-4">
                                <Loader2 className="w-4 h-4 text-gray-400 animate-spin" />
                            </div>
                        ) : allBots.length === 0 ? (
                            <div className="px-3 py-4 text-center text-sm text-gray-400">
                                {t('No bots in the system')}
                            </div>
                        ) : (
                            allBots.map((bot) => {
                                const isLinked = linkedBotIds.has(bot.id)
                                return (
                                    <button
                                        key={bot.id}
                                        onClick={() => handleToggleBot(bot.id)}
                                        disabled={isMutating}
                                        className={`w-full flex items-center gap-2 px-3 py-2 text-sm transition-colors text-right disabled:opacity-50 ${
                                            isLinked
                                                ? 'bg-primary-50 text-primary-700 hover:bg-primary-100'
                                                : 'text-gray-700 hover:bg-gray-50'
                                        }`}
                                    >
                                        <div className={`w-4 h-4 rounded border flex items-center justify-center flex-shrink-0 ${
                                            isLinked
                                                ? 'bg-primary-600 border-primary-600'
                                                : 'border-gray-300'
                                        }`}>
                                            {isLinked && <Check className="w-3 h-3 text-white" />}
                                        </div>
                                        <Bot className={`w-3.5 h-3.5 flex-shrink-0 ${isLinked ? 'text-primary-500' : 'text-gray-400'}`} />
                                        <span className="truncate flex-1">{bot.bot_name}</span>
                                        {isMutating && (
                                            <Loader2 className="w-3 h-3 text-gray-400 animate-spin flex-shrink-0" />
                                        )}
                                    </button>
                                )
                            })
                        )}
                    </div>
                </div>
            )}
        </div>
    )
}
