/**
 * Opening Screen Presets Management Page
 * @since 1.1.0
 * @updated 1.5.1 - Added bulk delete functionality
 */

import { useState } from 'react'
import { Link } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Plus, Edit2, Trash2, Star, MessageSquare, Copy, Sparkles, ListChecks, Users, CheckSquare, Square, X } from 'lucide-react'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardContent } from '@/components/common/Card'
import { QuickBotAssign } from '@/components/common/QuickBotAssign'
import { apiClient } from '@/api/client'
import { t, sprintf } from '@/lib/i18n'
import { useLanguage } from '@/contexts/LanguageContext'

interface Question {
    text: string
    icon: string
}

interface QAPair {
    question: string
    answer: string
    icon: string
}

interface OpeningScreenPreset {
    id: number
    name: string
    slug: string
    description: string | null
    is_default: number
    is_system: number
    mode: 'questions_ai' | 'questions_answers' | 'departments'
    welcome_text: string | null
    show_welcome: number
    questions: Question[]
    ai_instructions: string | null
    qa_pairs: QAPair[]
    contact_list_id: number | null
    show_departments: number
    show_contact_cards: number
    attached_files: Array<{ name: string; type: string }>
}

const modeIcons: Record<string, typeof Sparkles> = {
    questions_ai: Sparkles,
    questions_answers: ListChecks,
    // departments: Users, // Temporarily disabled
}

const modeLabels: Record<string, () => string> = {
    questions_ai: () => t('Questions + AI'),
    questions_answers: () => t('Questions + Answers'),
    // departments: () => t('Departments'), // Temporarily disabled
}

export function OpeningScreenPresets() {
    const queryClient = useQueryClient()
    const { currentLanguage } = useLanguage()
    const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set())
    const [isSelectionMode, setIsSelectionMode] = useState(false)

    const { data, isLoading } = useQuery({
        queryKey: ['opening-screen-presets', currentLanguage],
        queryFn: () => apiClient.get<{ data: { presets: OpeningScreenPreset[] } }>('opening-screen-presets', { language: currentLanguage }),
    })

    const deletePreset = useMutation({
        mutationFn: (id: number) => apiClient.delete(`opening-screen-presets/${id}`),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['opening-screen-presets', currentLanguage] })
        },
        onError: (error: any) => {
            console.error('Delete failed:', error)
            alert(sprintf(t('Delete error: %s'), error?.message || t('Unknown error')))
        },
    })

    const bulkDeletePresets = useMutation({
        mutationFn: (ids: number[]) => apiClient.post('opening-screen-presets/bulk-delete', { ids }),
        onSuccess: (response: any) => {
            queryClient.invalidateQueries({ queryKey: ['opening-screen-presets', currentLanguage] })
            setSelectedIds(new Set())
            setIsSelectionMode(false)
            alert(response?.data?.message || t('Items deleted successfully'))
        },
        onError: (error: any) => {
            console.error('Bulk delete failed:', error)
            alert(sprintf(t('Delete error: %s'), error?.message || t('Unknown error')))
        },
    })

    const setDefault = useMutation({
        mutationFn: (id: number) => apiClient.post(`opening-screen-presets/${id}/set-default`, {}),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['opening-screen-presets', currentLanguage] })
        },
        onError: (error: any) => {
            console.error('Set default failed:', error)
            alert(sprintf(t('Error setting default: %s'), error?.message || t('Unknown error')))
        },
    })

    const duplicatePreset = useMutation({
        mutationFn: (id: number) => apiClient.post(`opening-screen-presets/${id}/duplicate`, {}),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['opening-screen-presets', currentLanguage] })
        },
        onError: () => {
            alert(t('Failed to duplicate preset. Please try again.'))
        },
    })

    const presets = data?.data?.presets || []
    
    // Filter out system presets for selection (can't delete them)
    const selectablePresets = presets.filter(p => p.is_system !== 1)

    const handleDelete = (id: number, name: string, isSystem: boolean) => {
        if (isSystem) {
            alert(t('Cannot delete a system opening screen preset'))
            return
        }
        if (confirm(sprintf(t('Are you sure you want to delete "%s"?'), name))) {
            deletePreset.mutate(id)
        }
    }

    const handleBulkDelete = () => {
        if (selectedIds.size === 0) return
        
        if (confirm(sprintf(t('Are you sure you want to delete %d opening screen presets?'), selectedIds.size))) {
            bulkDeletePresets.mutate(Array.from(selectedIds))
        }
    }

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

    const handleSelectAll = () => {
        if (selectedIds.size === selectablePresets.length) {
            setSelectedIds(new Set())
        } else {
            setSelectedIds(new Set(selectablePresets.map(p => p.id)))
        }
    }

    const handleSetDefault = (id: number) => {
        setDefault.mutate(id)
    }

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

    const exitSelectionMode = () => {
        setIsSelectionMode(false)
        setSelectedIds(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 animate-fade-in">
            <PageHeader
                title={t('Opening Screen')}
                subtitle={t('Manage opening screen presets for bots')}
            >
                <div className="flex items-center gap-2">
                    {!isSelectionMode ? (
                        <>
                            {selectablePresets.length > 0 && (
                                <button
                                    onClick={() => setIsSelectionMode(true)}
                                    className="flex items-center gap-2 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                                >
                                    <CheckSquare className="w-4 h-4" />
                                    {t('Select Multiple')}
                                </button>
                            )}
                            <Link
                                to="/opening-screen-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('Add Opening Screen')}
                            </Link>
                        </>
                    ) : (
                        <>
                            <span className="text-sm text-gray-600">
                                {sprintf(t('%d selected'), selectedIds.size)}
                            </span>
                            <button
                                onClick={handleSelectAll}
                                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 text-sm"
                            >
                                {selectedIds.size === selectablePresets.length ? t('Deselect All') : t('Select All')}
                            </button>
                            <button
                                onClick={handleBulkDelete}
                                disabled={selectedIds.size === 0 || bulkDeletePresets.isPending}
                                className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                                {bulkDeletePresets.isPending ? (
                                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                                ) : (
                                    <Trash2 className="w-4 h-4" />
                                )}
                                {t('Delete Selected')}
                            </button>
                            <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>

            {presets.length === 0 ? (
                <Card>
                    <CardContent className="py-16 text-center">
                        <MessageSquare 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 Opening Screen Presets')}
                        </h3>
                        <p className="text-gray-500 mb-6">
                            {t('Create your first opening screen to customize the opening experience')}
                        </p>
                        <Link
                            to="/opening-screen-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 Opening Screen')}
                        </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, preset.is_system === 1)}
                            onSetDefault={() => handleSetDefault(preset.id)}
                            onDuplicate={() => handleDuplicate(preset.id)}
                            isSelectionMode={isSelectionMode}
                            isSelected={selectedIds.has(preset.id)}
                            onToggleSelection={() => handleToggleSelection(preset.id)}
                        />
                    ))}
                </div>
            )}
        </div>
    )
}

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

function PresetCard({ preset, onDelete, onSetDefault, onDuplicate, isSelectionMode, isSelected, onToggleSelection }: PresetCardProps) {
    const ModeIcon = modeIcons[preset.mode] || Sparkles
    const modeLabel = modeLabels[preset.mode]?.() || preset.mode
    
    const getPreviewContent = () => {
        switch (preset.mode) {
            case 'questions_ai':
                return (
                    <div className="space-y-2">
                        {(preset.questions || []).slice(0, 3).map((q, idx) => (
                            <div key={idx} className="px-3 py-1.5 bg-white/80 rounded-full text-xs text-gray-700 truncate">
                                {q.icon && <span className="me-1">{q.icon}</span>}
                                {q.text}
                            </div>
                        ))}
                    </div>
                )
            case 'questions_answers':
                return (
                    <div className="space-y-2">
                        {(preset.qa_pairs || []).slice(0, 2).map((qa, idx) => (
                            <div key={idx} className="px-3 py-1.5 bg-white/80 rounded text-xs text-gray-700 truncate">
                                {qa.icon && <span className="me-1">{qa.icon}</span>}
                                {qa.question}
                            </div>
                        ))}
                    </div>
                )
            case 'departments':
                return (
                    <div className="px-3 py-2 bg-white/80 rounded text-xs text-gray-600">
                        <Users className="w-4 h-4 inline me-1" />
                        {t('Departments and contacts view')}
                    </div>
                )
            default:
                return null
        }
    }
    
    const canSelect = 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 right-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>
            )}
            
            {/* Preview Header */}
            <div className="relative bg-gradient-to-br from-primary-50 to-primary-100 p-4 min-h-[160px]">
                {/* Mode Badge */}
                <div className="absolute top-3 left-3 flex items-center gap-1.5 px-2 py-1 bg-white/90 rounded-full text-xs font-medium text-gray-700">
                    <ModeIcon className="w-3.5 h-3.5 text-primary-600" />
                    {modeLabel}
                </div>

                {/* Default Badge - move down when selection mode is active */}
                {preset.is_default === 1 && (
                    <div className={`absolute ${isSelectionMode && canSelect ? 'top-12' : 'top-3'} right-3 flex items-center gap-1 px-2 py-1 bg-yellow-100 text-yellow-700 rounded-full text-xs font-medium transition-all`}>
                        <Star className="w-3 h-3 fill-current" />
                        {t('Default')}
                    </div>
                )}

                {/* System Badge */}
                {preset.is_system === 1 && preset.is_default !== 1 && (
                    <div className="absolute top-3 right-3 px-2 py-1 bg-gray-100 text-gray-600 rounded-full text-xs font-medium">
                        {t('System')}
                    </div>
                )}

                {/* Welcome Text Preview */}
                {preset.show_welcome === 1 && preset.welcome_text && (
                    <div className="mt-10 mb-3 text-center">
                        <div className="inline-block px-4 py-2 bg-white rounded-lg shadow-sm text-sm text-gray-800">
                            {preset.welcome_text}
                        </div>
                    </div>
                )}

                {/* Mode-specific Preview */}
                <div className="mt-2">
                    {getPreviewContent()}
                </div>
            </div>

            {/* Card Body */}
            <CardContent className="p-4 bg-white">
                <div className="flex items-start justify-between">
                    <div className="flex-1 min-w-0">
                        <h3 className="font-semibold text-gray-900 truncate">{preset.name}</h3>
                        {preset.description && (
                            <p className="text-sm text-gray-500 mt-1 line-clamp-2">{preset.description}</p>
                        )}
                    </div>
                </div>

                {/* Actions */}
                <div className="flex items-center gap-2 mt-4 pt-4 border-t">
                    <Link
                        to={`/opening-screen-presets/${preset.id}`}
                        className="flex items-center gap-1 px-3 py-1.5 bg-primary-50 text-primary-600 rounded-lg hover:bg-primary-100 transition-colors text-sm"
                    >
                        <Edit2 className="w-3.5 h-3.5" />
                        {t('Edit')}
                    </Link>

                    <button
                        onClick={onDuplicate}
                        className="flex items-center gap-1 px-3 py-1.5 bg-gray-50 text-gray-600 rounded-lg hover:bg-gray-100 transition-colors text-sm"
                        title={t('Duplicate')}
                    >
                        <Copy className="w-3.5 h-3.5" />
                    </button>

                    {preset.is_default !== 1 && (
                        <button
                            onClick={onSetDefault}
                            className="flex items-center gap-1 px-3 py-1.5 bg-gray-50 text-gray-600 rounded-lg hover:bg-yellow-50 hover:text-yellow-600 transition-colors text-sm"
                            title={t('Set as Default')}
                        >
                            <Star className="w-3.5 h-3.5" />
                        </button>
                    )}

                    <QuickBotAssign
                        entityType="opening-screen-preset"
                        entityId={preset.id}
                    />

                    {preset.is_system !== 1 && (
                        <button
                            onClick={onDelete}
                            className="flex items-center gap-1 px-3 py-1.5 bg-gray-50 text-gray-600 rounded-lg hover:bg-red-50 hover:text-red-600 transition-colors text-sm ms-auto"
                            title={t('Delete')}
                        >
                            <Trash2 className="w-3.5 h-3.5" />
                        </button>
                    )}
                </div>
            </CardContent>
        </Card>
    )
}

export default OpeningScreenPresets
