/**
 * LinkedBotsSection Component
 * Shows a list of bots linked to a preset (Personality, Appearance, Widget, Opening Screen)
 * with the ability to unlink and assign bots
 */
import { useState, useRef, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Bot, Link2Off, Link2, ChevronDown, Check, Loader2 } from 'lucide-react'
import { Link } from 'react-router-dom'
import { apiClient } from '@/api/client'
import { Card, CardHeader, CardTitle, CardContent } from './Card'
import { t, sprintf } from '@/lib/i18n'

interface LinkedBot {
    id: number
    bot_name: string
}

interface AllBot {
    id: number
    bot_name: string
}

interface LinkedBotsSectionProps {
    entityType: 'personality' | 'appearance-preset' | 'widget' | 'opening-screen-preset'
    entityId: number
    onUnlink?: (botId: number) => void
    onLink?: (botId: number) => void
}

const ENTITY_LABELS: Record<string, { title: string; unlinkMessage: string; unlinkDescription: string }> = {
    'personality': {
        title: t('Personality'),
        unlinkMessage: t('Unlink bot "%s" from the personality?'),
        unlinkDescription: t('Unlinking will keep current settings but stop syncing them from the personality.'),
    },
    'appearance-preset': {
        title: t('Appearance Preset'),
        unlinkMessage: t('Unlink bot "%s" from the appearance preset?'),
        unlinkDescription: t('Unlinking will keep current settings but stop syncing them from the preset.'),
    },
    'widget': {
        title: t('Widget'),
        unlinkMessage: t('Unlink bot "%s" from the widget?'),
        unlinkDescription: t('Unlinking will remove the widget from the bot\'s widget list.'),
    },
    'opening-screen-preset': {
        title: t('Opening Message'),
        unlinkMessage: t('Unlink bot "%s" from the opening message?'),
        unlinkDescription: t('Unlinking will keep the current opening message settings on the bot.'),
    },
}

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

export function LinkedBotsSection({ entityType, entityId, onUnlink, onLink }: LinkedBotsSectionProps) {
    const queryClient = useQueryClient()
    const apiEndpoint = ENTITY_API_MAP[entityType]
    const labels = ENTITY_LABELS[entityType]
    const [showAssignDropdown, setShowAssignDropdown] = useState(false)
    const dropdownRef = useRef<HTMLDivElement>(null)

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

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

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

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

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

    const linkedBots = data?.data?.bots || []
    const allBots = allBotsData?.data?.bots || []
    const linkedBotIds = new Set(linkedBots.map(b => b.id))
    const availableBots = allBots.filter(b => !linkedBotIds.has(b.id))

    // Show loading state
    if (isLoading) {
        return (
            <Card className="mt-6">
                <CardContent className="p-6">
                    <div className="text-center text-gray-400">
                        <Bot className="w-6 h-6 mx-auto mb-2 animate-pulse" />
                        {t('Loading linked bots...')}
                    </div>
                </CardContent>
            </Card>
        )
    }

    const handleUnlink = (bot: LinkedBot) => {
        const message = sprintf(labels.unlinkMessage, bot.bot_name)
        if (confirm(message)) {
            unlinkMutation.mutate(bot.id)
        }
    }

    const handleLink = (bot: AllBot) => {
        linkMutation.mutate(bot.id)
    }

    return (
        <Card className="mt-6">
            <CardHeader>
                <div className="flex items-center justify-between">
                    <CardTitle className="text-base flex items-center gap-2">
                        <Bot className="w-4 h-4 text-primary-600" />
                        {sprintf(t('Bots using this %s (%d)'), labels.title, linkedBots.length)}
                    </CardTitle>
                    
                    {/* Assign Bot Button */}
                    <div className="relative" ref={dropdownRef}>
                        <button
                            onClick={() => setShowAssignDropdown(!showAssignDropdown)}
                            className="flex items-center gap-1.5 px-3 py-1.5 text-sm bg-primary-50 text-primary-700 rounded-lg hover:bg-primary-100 transition-colors"
                        >
                            <Link2 className="w-3.5 h-3.5" />
                            {t('Assign Bot')}
                            <ChevronDown className={`w-3.5 h-3.5 transition-transform ${showAssignDropdown ? 'rotate-180' : ''}`} />
                        </button>

                        {/* Assign Dropdown */}
                        {showAssignDropdown && (
                            <div className="absolute end-0 mt-1 w-64 bg-white rounded-lg shadow-xl border border-gray-200 z-50 overflow-hidden">
                                <div className="px-3 py-2 bg-gray-50 border-b border-gray-200">
                                    <span className="text-xs font-medium text-gray-500">{t('Select bots to assign')}</span>
                                </div>
                                <div className="max-h-48 overflow-y-auto">
                                    {availableBots.length === 0 ? (
                                        <div className="px-3 py-4 text-center text-sm text-gray-400">
                                            {allBots.length === 0 ? t('Loading bots...') : t('All bots already assigned')}
                                        </div>
                                    ) : (
                                        availableBots.map((bot) => (
                                            <button
                                                key={bot.id}
                                                onClick={() => handleLink(bot)}
                                                disabled={linkMutation.isPending}
                                                className="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-primary-50 transition-colors text-right disabled:opacity-50"
                                            >
                                                <Bot className="w-3.5 h-3.5 text-gray-400 flex-shrink-0" />
                                                <span className="truncate flex-1">{bot.bot_name}</span>
                                                {linkMutation.isPending ? (
                                                    <Loader2 className="w-3.5 h-3.5 text-primary-600 animate-spin flex-shrink-0" />
                                                ) : (
                                                    <Link2 className="w-3.5 h-3.5 text-primary-400 opacity-0 group-hover:opacity-100 flex-shrink-0" />
                                                )}
                                            </button>
                                        ))
                                    )}
                                </div>
                                
                                {/* Show already linked bots */}
                                {linkedBots.length > 0 && (
                                    <>
                                        <div className="px-3 py-2 bg-gray-50 border-t border-gray-200">
                                            <span className="text-xs font-medium text-gray-400">{t('Already assigned')}</span>
                                        </div>
                                        <div className="max-h-32 overflow-y-auto">
                                            {linkedBots.map((bot) => (
                                                <div
                                                    key={bot.id}
                                                    className="flex items-center gap-2 px-3 py-2 text-sm text-gray-400"
                                                >
                                                    <Bot className="w-3.5 h-3.5 flex-shrink-0" />
                                                    <span className="truncate flex-1">{bot.bot_name}</span>
                                                    <Check className="w-3.5 h-3.5 text-green-500 flex-shrink-0" />
                                                </div>
                                            ))}
                                        </div>
                                    </>
                                )}
                            </div>
                        )}
                    </div>
                </div>
            </CardHeader>
            <CardContent>
                {linkedBots.length === 0 ? (
                    <div className="text-center py-6 text-gray-400">
                        <Bot className="w-8 h-8 mx-auto mb-2 opacity-50" />
                        <p className="text-sm">{t('No bots assigned yet')}</p>
                        <p className="text-xs mt-1">{t('Click "Assign Bot" above to assign bots')}</p>
                    </div>
                ) : (
                    <div className="space-y-2">
                        {linkedBots.map((bot) => (
                            <div 
                                key={bot.id}
                                className="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors"
                            >
                                <Link 
                                    to={`/bots/${bot.id}`}
                                    className="flex items-center gap-3 flex-1"
                                >
                                    <Bot className="w-4 h-4 text-gray-400" />
                                    <span className="font-medium text-gray-900 hover:text-primary-600 transition-colors">
                                        {bot.bot_name}
                                    </span>
                                </Link>
                                <button
                                    onClick={() => handleUnlink(bot)}
                                    disabled={unlinkMutation.isPending}
                                    className="flex items-center gap-1 px-2 py-1 text-xs text-red-600 hover:bg-red-50 rounded transition-colors disabled:opacity-50"
                                    title={t('Unlink bot')}
                                >
                                    <Link2Off className="w-3 h-3" />
                                    {t('Unlink')}
                                </button>
                            </div>
                        ))}
                    </div>
                )}
                
                <p className="text-xs text-gray-400 mt-3">
                    {labels.unlinkDescription}
                </p>
            </CardContent>
        </Card>
    )
}
