import { useState, useRef, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useSearchParams, useNavigate } from 'react-router-dom'
import { 
    Plus, Users, Star, ChevronDown, ChevronUp, Trash2, 
    Upload, Phone, Mail, MessageCircle, X, Save, UserPlus, Edit2, ArrowRight, CalendarClock
} from 'lucide-react'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardContent, CardTitle } from '@/components/common/Card'
import { Button } from '@/components/common/Button'
import { apiClient } from '@/api/client'
import { AvailabilityScheduleEditor, type MeetingAvailability, parseMeetingAvailabilitySafely } from '@/components/contacts/AvailabilityScheduleEditor'
import { t, sprintf } from '@/lib/i18n'

interface Contact {
    id: number
    list_id: number
    name: string
    title: string | null
    department: string | null
    phone: string | null
    email: string | null
    whatsapp: string | null
    description: string | null
    meeting_availability: string | MeetingAvailability | null
    sort_order: number
}

interface ContactList {
    id: number
    name: string
    description: string | null
    is_primary: number
    contacts_count: number
    contacts?: Contact[]
}

interface NewContactForm {
    name: string
    title: string
    phonePrefix: string
    phone: string
    email: string
    whatsappPrefix: string
    whatsapp: string
    meeting_availability: MeetingAvailability | null
}

interface NewContactPayload {
    name: string
    title: string
    phone: string
    email: string
    whatsapp: string
    meeting_availability: MeetingAvailability | null
}

// Common phone prefixes for datalist suggestions
const PHONE_PREFIXES = [
    '+972',
    '+1',
    '+44',
    '+49',
    '+33',
    '+34',
    '+39',
    '+7',
    '+86',
    '+91',
]

const emptyContact: NewContactForm = {
    name: '',
    title: '',
    phonePrefix: '+972',
    phone: '',
    email: '',
    whatsappPrefix: '+972',
    whatsapp: '',
    meeting_availability: null,
}


export function ContactLists() {
    const queryClient = useQueryClient()
    const navigate = useNavigate()
    const [searchParams] = useSearchParams()
    const returnTo = searchParams.get('returnTo')
    const expandFromUrl = searchParams.get('expand')
    
    const [expandedList, setExpandedList] = useState<number | null>(null)
    const [showNewListForm, setShowNewListForm] = useState(false)
    
    // Auto-expand list if URL parameter is set
    useEffect(() => {
        if (expandFromUrl) {
            const expandId = Number(expandFromUrl)
            if (Number.isFinite(expandId) && expandId > 0) {
                setExpandedList(expandId)
            }
        }
    }, [expandFromUrl])
    const [newListName, setNewListName] = useState('')
    const [newListDescription, setNewListDescription] = useState('')
    const [newContact, setNewContact] = useState<NewContactForm>(emptyContact)
    const [addingToList, setAddingToList] = useState<number | null>(null)
    const fileInputRef = useRef<HTMLInputElement>(null)
    const [importingToList, setImportingToList] = useState<number | null>(null)
    const [editingList, setEditingList] = useState<number | null>(null)
    const [editListName, setEditListName] = useState('')
    const [editListDescription, setEditListDescription] = useState('')
    const [editingContact, setEditingContact] = useState<Contact | null>(null)
    const [availContactId, setAvailContactId] = useState<number | null>(null)
    const [isNewContactAvailabilityOpen, setIsNewContactAvailabilityOpen] = useState(false)
    const [isSavingAvailability, setIsSavingAvailability] = useState(false)

    // Fetch lists
    const { data: listsData, isLoading } = useQuery({
        queryKey: ['contact-lists'],
        queryFn: () => apiClient.get<{ data: { lists: ContactList[] } }>('contact-lists'),
    })

    // Fetch single list with contacts
    const { data: expandedListData } = useQuery({
        queryKey: ['contact-list', expandedList],
        queryFn: () => apiClient.get<{ data: { list: ContactList } }>(`contact-lists/${expandedList}`),
        enabled: !!expandedList,
    })

    // Create list mutation
    const createList = useMutation({
        mutationFn: (data: { name: string; description?: string }) => 
            apiClient.post('contact-lists', data),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['contact-lists'] })
            setShowNewListForm(false)
            setNewListName('')
            setNewListDescription('')
        },
        onError: () => {
            alert(t('Failed to create contact list.'))
        },
    })

    // Delete list mutation
    const deleteList = useMutation({
        mutationFn: (id: number) => apiClient.delete(`contact-lists/${id}`),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['contact-lists'] })
            if (expandedList) setExpandedList(null)
        },
        onError: () => {
            alert(t('Failed to delete contact list.'))
        },
    })

    // Set primary mutation
    const setPrimary = useMutation({
        mutationFn: (id: number) => apiClient.put(`contact-lists/${id}/primary`, {}),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['contact-lists'] })
        },
        onError: () => {
            alert(t('Operation failed. Please try again.'))
        },
    })

    // Update list mutation
    const updateList = useMutation({
        mutationFn: ({ id, data }: { id: number; data: { name: string; description?: string } }) =>
            apiClient.put(`contact-lists/${id}`, data),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['contact-lists'] })
            setEditingList(null)
            setEditListName('')
            setEditListDescription('')
        },
        onError: () => {
            alert(t('Operation failed. Please try again.'))
        },
    })

    // Add contact mutation
    const addContact = useMutation({
        mutationFn: ({ listId, data }: { listId: number; data: NewContactPayload }) =>
            apiClient.post(`contact-lists/${listId}/contacts`, data),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['contact-list', addingToList] })
            queryClient.invalidateQueries({ queryKey: ['contact-lists'] })
            setNewContact(emptyContact)
            setAddingToList(null)
        },
        onError: () => {
            alert(t('Operation failed. Please try again.'))
        },
    })

    // Delete contact mutation
    const deleteContact = useMutation({
        mutationFn: ({ listId, contactId }: { listId: number; contactId: number }) =>
            apiClient.delete(`contact-lists/${listId}/contacts/${contactId}`),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['contact-list', expandedList] })
            queryClient.invalidateQueries({ queryKey: ['contact-lists'] })
        },
        onError: () => {
            alert(t('Operation failed. Please try again.'))
        },
    })

    // Update contact mutation
    const updateContact = useMutation({
        mutationFn: ({ listId, contactId, data }: { listId: number; contactId: number; data: Partial<Contact> }) =>
            apiClient.put(`contact-lists/${listId}/contacts/${contactId}`, data),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['contact-list', expandedList] })
            setEditingContact(null)
        },
        onError: () => {
            alert(t('Operation failed. Please try again.'))
        },
    })

    // Import contacts mutation - reads file and sends content as JSON
    const importContacts = useMutation({
        mutationFn: async ({ listId, file }: { listId: number; file: File }) => {
            const MAX_CSV_SIZE = 5 * 1024 * 1024
            if (file.size > MAX_CSV_SIZE) {
                throw new Error(t('CSV file is too large. Maximum size is 5MB.'))
            }

            const content = await file.text()
            
            return apiClient.post(`contact-lists/${listId}/import`, {
                csv_content: content,
            })
        },
        onSuccess: (data) => {
            queryClient.invalidateQueries({ queryKey: ['contact-list', importingToList] })
            queryClient.invalidateQueries({ queryKey: ['contact-lists'] })
            const response = data as { data?: { message?: string } }
            alert(response?.data?.message || t('Import completed'))
            setImportingToList(null)
        },
        onError: (error: Error) => {
            alert(sprintf(t('Error importing file: %s'), error.message))
        },
    })

    const lists = listsData?.data?.lists || []
    const contacts = expandedListData?.data?.list?.contacts || []

    const handleToggleList = (id: number) => {
        setExpandedList(expandedList === id ? null : id)
        setAddingToList(null)
    }

    const handleCreateList = () => {
        if (newListName.trim()) {
            createList.mutate({
                name: newListName.trim(),
                description: newListDescription.trim() || undefined,
            })
        }
    }

    const handleDeleteList = (id: number, name: string) => {
        if (confirm(sprintf(t('Are you sure you want to delete the list "%s"? All contacts will be deleted.'), name))) {
            deleteList.mutate(id)
        }
    }

    const handleAddContact = (listId: number) => {
        if (newContact.name.trim()) {
            // Combine prefix with phone numbers
            const dataToSend = {
                name: newContact.name,
                title: newContact.title,
                phone: newContact.phone ? `${newContact.phonePrefix}${newContact.phone.replace(/^0/, '')}` : '',
                email: newContact.email,
                whatsapp: newContact.whatsapp ? `${newContact.whatsappPrefix}${newContact.whatsapp.replace(/^0/, '')}` : '',
                meeting_availability: newContact.meeting_availability,
            }
            addContact.mutate({ listId, data: dataToSend })
        }
    }

    const handleEditList = (list: ContactList) => {
        setEditingList(list.id)
        setEditListName(list.name)
        setEditListDescription(list.description || '')
    }

    const handleSaveListEdit = () => {
        if (editingList && editListName.trim()) {
            updateList.mutate({
                id: editingList,
                data: {
                    name: editListName.trim(),
                    description: editListDescription.trim() || undefined,
                },
            })
        }
    }

    const handleDeleteContact = (listId: number, contactId: number, name: string) => {
        if (confirm(sprintf(t('Are you sure you want to delete "%s"?'), name))) {
            deleteContact.mutate({ listId, contactId })
        }
    }

    const handleEditContact = (contact: Contact) => {
        setEditingContact({ ...contact })
    }

    const handleSaveContact = () => {
        if (editingContact && expandedList) {
            updateContact.mutate({
                listId: expandedList,
                contactId: editingContact.id,
                data: {
                    name: editingContact.name,
                    title: editingContact.title,
                    phone: editingContact.phone,
                    email: editingContact.email,
                    whatsapp: editingContact.whatsapp,
                },
            })
        }
    }

    const handleOpenAvailability = (contact: Contact) => {
        setAvailContactId(Number(contact.id))
    }

    const handleOpenNewContactAvailability = () => {
        setIsNewContactAvailabilityOpen(true)
    }

    const handleSaveAvailability = async (data: MeetingAvailability) => {
        if (isNewContactAvailabilityOpen) {
            setNewContact((prev) => ({
                ...prev,
                meeting_availability: data,
            }))
            return
        }
        if (!availContactId || !expandedList) return
        setIsSavingAvailability(true)
        try {
            await apiClient.put(
                `contact-lists/${expandedList}/contacts/${availContactId}`,
                { meeting_availability: data }
            )
            await queryClient.invalidateQueries({ queryKey: ['contact-list', expandedList] })
            // Don't close here — the editor calls onClose() after onSave resolves
        } catch (err) {
            console.error('Failed to save availability:', err)
            throw err // Re-throw so the editor knows the save failed
        } finally {
            setIsSavingAvailability(false)
        }
    }

    const handleImportClick = (listId: number) => {
        setImportingToList(listId)
        fileInputRef.current?.click()
    }

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0]
        if (!file) {
            setImportingToList(null)
            return
        }
        if (importingToList) {
            importContacts.mutate({ listId: importingToList, file })
        }
        e.target.value = ''
    }

    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('Contact Lists')} 
                subtitle={t('Manage contacts that the bot will show to customers')}
            >
                <div className="flex gap-2">
                    {returnTo && (
                        <Button variant="outline" onClick={() => navigate(returnTo)}>
                            <ArrowRight className="w-4 h-4 me-2" />
                            {t('Back to bot')}
                        </Button>
                    )}
                    <Button onClick={() => setShowNewListForm(true)}>
                        <Plus className="w-4 h-4 me-2" />
                        {t('New List')}
                    </Button>
                </div>
            </PageHeader>

            {/* Hidden file input for import */}
            <input
                ref={fileInputRef}
                type="file"
                accept=".csv"
                className="hidden"
                onChange={handleFileChange}
            />

            {/* New List Form */}
            {showNewListForm && (
                <Card className="border-primary-200 bg-primary-50">
                    <CardContent className="pt-6">
                        <div className="flex items-end gap-4">
                            <div className="flex-1">
                                <label className="block text-sm font-medium mb-1">{t('List Name')}</label>
                                <input
                                    type="text"
                                    value={newListName}
                                    onChange={(e) => setNewListName(e.target.value)}
                                    placeholder={t('e.g.: Sales team')}
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                                />
                            </div>
                            <div className="flex-1">
                                <label className="block text-sm font-medium mb-1">{t('Description (optional)')}</label>
                                <input
                                    type="text"
                                    value={newListDescription}
                                    onChange={(e) => setNewListDescription(e.target.value)}
                                    placeholder={t('Short description')}
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                                />
                            </div>
                            <Button onClick={handleCreateList} disabled={!newListName.trim()}>
                                <Save className="w-4 h-4 me-1" />
                                {t('Save')}
                            </Button>
                            <Button variant="outline" onClick={() => setShowNewListForm(false)}>
                                <X className="w-4 h-4" />
                            </Button>
                        </div>
                    </CardContent>
                </Card>
            )}

            {/* Lists */}
            <div className="space-y-4">
                {lists.map((list) => (
                    <Card key={list.id} className={expandedList === list.id ? 'ring-2 ring-primary-200' : ''}>
                        <div 
                            className="p-4 cursor-pointer hover:bg-gray-50 transition-colors"
                            onClick={() => handleToggleList(list.id)}
                        >
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-3">
                                    {list.is_primary === 1 && (
                                        <span className="flex items-center gap-1 px-2 py-1 bg-yellow-100 text-yellow-800 text-xs font-medium rounded-full">
                                            <Star className="w-3 h-3" />
                                            {t('Primary')}
                                        </span>
                                    )}
                                    <CardTitle className="flex items-center gap-2">
                                        <Users className="w-5 h-5 text-primary-600" />
                                        {list.name}
                                    </CardTitle>
                                    <span className="text-sm text-gray-500">
                                        {sprintf(t('(%s contacts)'), list.contacts_count || 0)}
                                    </span>
                                </div>
                                <div className="flex items-center gap-2">
                                    {list.is_primary !== 1 && (
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            onClick={(e) => {
                                                (e as React.MouseEvent).stopPropagation()
                                                setPrimary.mutate(list.id)
                                            }}
                                            title={t('Set as Primary')}
                                        >
                                            <Star className="w-4 h-4" />
                                        </Button>
                                    )}
                                    <Button
                                        variant="ghost"
                                        size="sm"
                                        onClick={(e) => {
                                            (e as React.MouseEvent).stopPropagation()
                                            handleEditList(list)
                                        }}
                                        title={t('Edit list')}
                                    >
                                        <Edit2 className="w-4 h-4" />
                                    </Button>
                                    <Button
                                        variant="ghost"
                                        size="sm"
                                        onClick={(e) => {
                                            (e as React.MouseEvent).stopPropagation()
                                            handleDeleteList(list.id, list.name)
                                        }}
                                        className="text-red-600 hover:bg-red-50"
                                    >
                                        <Trash2 className="w-4 h-4" />
                                    </Button>
                                    {expandedList === list.id ? (
                                        <ChevronUp className="w-5 h-5 text-gray-400" />
                                    ) : (
                                        <ChevronDown className="w-5 h-5 text-gray-400" />
                                    )}
                                </div>
                            </div>
                        </div>

                        {/* Edit List Modal */}
                        {editingList === list.id && (
                            <div className="px-4 py-3 bg-blue-50 border-b border-blue-100">
                                <h4 className="font-medium text-blue-900 mb-3">{t('Edit List')}</h4>
                                <div className="flex gap-2 items-end">
                                    <div className="flex-1">
                                        <label className="block text-sm text-gray-600 mb-1">{t('List Name')}</label>
                                        <input
                                            type="text"
                                            value={editListName}
                                            onChange={(e) => setEditListName(e.target.value)}
                                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                                        />
                                    </div>
                                    <div className="flex-1">
                                        <label className="block text-sm text-gray-600 mb-1">{t('Description')}</label>
                                        <input
                                            type="text"
                                            value={editListDescription}
                                            onChange={(e) => setEditListDescription(e.target.value)}
                                            placeholder={t('Short description')}
                                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
                                        />
                                    </div>
                                    <Button onClick={handleSaveListEdit} disabled={!editListName.trim()}>
                                        <Save className="w-4 h-4 me-1" />
                                        {t('Save')}
                                    </Button>
                                    <Button variant="outline" onClick={() => setEditingList(null)}>
                                        <X className="w-4 h-4" />
                                    </Button>
                                </div>
                            </div>
                        )}

                        {expandedList === list.id && (
                            <CardContent className="pt-0">
                                {/* Actions */}
                                <div className="flex gap-2 mb-4 pb-4 border-b">
                                    <Button 
                                        variant="outline" 
                                        size="sm"
                                        onClick={() => setAddingToList(addingToList === list.id ? null : list.id)}
                                    >
                                        <UserPlus className="w-4 h-4 me-1" />
                                        {t('Add Manually')}
                                    </Button>
                                    <Button 
                                        variant="outline" 
                                        size="sm"
                                        onClick={() => handleImportClick(list.id)}
                                    >
                                        <Upload className="w-4 h-4 me-1" />
                                        {t('Import from CSV')}
                                    </Button>
                                </div>

                                {/* Add Contact Form */}
                                {addingToList === list.id && (
                                    <div className="mb-4 p-4 bg-gradient-to-b from-blue-50 to-white rounded-lg border border-blue-100">
                                        <h4 className="font-medium mb-4 text-blue-900 flex items-center gap-2">
                                            <UserPlus className="w-5 h-5" />
                                            {t('Add New Contact')}
                                        </h4>
                                        
                                        {/* Datalist for prefix suggestions */}
                                        <datalist id="phone-prefixes">
                                            {PHONE_PREFIXES.map((p) => (
                                                <option key={p} value={p} />
                                            ))}
                                        </datalist>
                                        
                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                            {/* Row 1: Name & Title */}
                                            <div>
                                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                                    {t('Name')} <span className="text-red-500">*</span>
                                                </label>
                                                <input
                                                    type="text"
                                                    value={newContact.name}
                                                    onChange={(e) => setNewContact({ ...newContact, name: e.target.value })}
                                                    placeholder={t('Full name')}
                                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                                />
                                            </div>
                                            <div>
                                                <label className="block text-sm font-medium text-gray-700 mb-1">{t('Title')}</label>
                                                <input
                                                    type="text"
                                                    value={newContact.title}
                                                    onChange={(e) => setNewContact({ ...newContact, title: e.target.value })}
                                                    placeholder={t('e.g.: Sales Manager')}
                                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                                />
                                            </div>
                                            
                                            {/* Row 2: Phone */}
                                            <div>
                                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                                    <Phone className="w-4 h-4 inline me-1" />
                                                    {t('Phone')}
                                                </label>
                                                <div className="flex gap-1">
                                                    <input
                                                        type="text"
                                                        value={newContact.phonePrefix}
                                                        onChange={(e) => setNewContact({ ...newContact, phonePrefix: e.target.value })}
                                                        list="phone-prefixes"
                                                        placeholder="+972"
                                                        className="w-20 px-2 py-2 border border-gray-300 rounded-lg text-center bg-gray-50 focus:ring-2 focus:ring-blue-500"
                                                        dir="ltr"
                                                    />
                                                    <input
                                                        type="tel"
                                                        value={newContact.phone}
                                                        onChange={(e) => setNewContact({ ...newContact, phone: e.target.value })}
                                                        placeholder={t('50-1234567')}
                                                        className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                                                        dir="ltr"
                                                    />
                                                </div>
                                            </div>
                                            
                                            {/* Row 2: Email */}
                                            <div>
                                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                                    <Mail className="w-4 h-4 inline me-1" />
                                                    {t('Email')}
                                                </label>
                                                <input
                                                    type="email"
                                                    value={newContact.email}
                                                    onChange={(e) => setNewContact({ ...newContact, email: e.target.value })}
                                                    placeholder={t('email@example.com')}
                                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                                                    dir="ltr"
                                                />
                                            </div>
                                            
                                            {/* Row 3: WhatsApp */}
                                            <div>
                                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                                    <MessageCircle className="w-4 h-4 inline me-1 text-green-600" />
                                                    {t('WhatsApp')}
                                                </label>
                                                <div className="flex gap-1">
                                                    <input
                                                        type="text"
                                                        value={newContact.whatsappPrefix}
                                                        onChange={(e) => setNewContact({ ...newContact, whatsappPrefix: e.target.value })}
                                                        list="phone-prefixes"
                                                        placeholder="+972"
                                                        className="w-20 px-2 py-2 border border-gray-300 rounded-lg text-center bg-gray-50 focus:ring-2 focus:ring-green-500"
                                                        dir="ltr"
                                                    />
                                                    <input
                                                        type="tel"
                                                        value={newContact.whatsapp}
                                                        onChange={(e) => setNewContact({ ...newContact, whatsapp: e.target.value })}
                                                        placeholder={t('50-1234567')}
                                                        className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"
                                                        dir="ltr"
                                                    />
                                                </div>
                                            </div>
                                            
                                            {/* Row 3: Availability */}
                                            <div>
                                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                                    {t('Availability Hours')}
                                                </label>
                                                <button
                                                    type="button"
                                                    onClick={handleOpenNewContactAvailability}
                                                    className={`inline-flex items-center gap-1 px-3 py-2 rounded-md text-sm transition-colors border ${
                                                        newContact.meeting_availability
                                                            ? 'text-primary-600 bg-primary-50 hover:bg-primary-100 border-primary-200'
                                                            : 'text-gray-500 hover:text-primary-600 hover:bg-gray-100 border-gray-300'
                                                    }`}
                                                    title={t('Set meeting availability')}
                                                >
                                                    <CalendarClock className="w-4 h-4" />
                                                    <span>{newContact.meeting_availability ? t('Configured') : t('Set meeting availability')}</span>
                                                </button>
                                            </div>
                                        </div>
                                        
                                        <div className="flex gap-2 mt-4 pt-3 border-t border-blue-100">
                                            <Button size="sm" onClick={() => handleAddContact(list.id)} disabled={!newContact.name.trim()}>
                                                <Save className="w-4 h-4 me-1" />
                                                {t('Save Contact')}
                                            </Button>
                                            <Button variant="outline" size="sm" onClick={() => {
                                                setAddingToList(null)
                                                setNewContact(emptyContact)
                                            }}>
                                                {t('Cancel')}
                                            </Button>
                                        </div>
                                    </div>
                                )}

                                {/* Contacts Table */}
                                {contacts.length > 0 ? (
                                    <div className="overflow-x-auto">
                                        <table className="w-full text-sm">
                                            <thead>
                                                <tr className="border-b bg-gray-50">
                                                    <th className="py-2 px-3 text-start font-medium">{t('Name')}</th>
                                                    <th className="py-2 px-3 text-start font-medium">{t('Title')}</th>
                                                    <th className="py-2 px-3 text-start font-medium">{t('Phone')}</th>
                                                    <th className="py-2 px-3 text-start font-medium">{t('Email')}</th>
                                                    <th className="py-2 px-3 text-start font-medium">{t('WhatsApp')}</th>
                                                    <th className="py-2 px-3 text-start font-medium">{t('Availability')}</th>
                                                    <th className="py-2 px-3 text-center font-medium w-20">{t('Actions')}</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {contacts.map((contact) => (
                                                    editingContact?.id === contact.id ? (
                                                        // Edit mode row
                                                        <tr key={contact.id} className="border-b bg-blue-50">
                                                            <td className="py-2 px-2">
                                                                <input
                                                                    type="text"
                                                                    value={editingContact.name}
                                                                    onChange={(e) => setEditingContact({ ...editingContact, name: e.target.value })}
                                                                    className="w-full px-2 py-1 border rounded text-sm"
                                                                />
                                                            </td>
                                                            <td className="py-2 px-2">
                                                                <input
                                                                    type="text"
                                                                    value={editingContact.title || ''}
                                                                    onChange={(e) => setEditingContact({ ...editingContact, title: e.target.value })}
                                                                    className="w-full px-2 py-1 border rounded text-sm"
                                                                />
                                                            </td>
                                                            <td className="py-2 px-2">
                                                                <input
                                                                    type="tel"
                                                                    value={editingContact.phone || ''}
                                                                    onChange={(e) => setEditingContact({ ...editingContact, phone: e.target.value })}
                                                                    className="w-full px-2 py-1 border rounded text-sm"
                                                                    dir="ltr"
                                                                />
                                                            </td>
                                                            <td className="py-2 px-2">
                                                                <input
                                                                    type="email"
                                                                    value={editingContact.email || ''}
                                                                    onChange={(e) => setEditingContact({ ...editingContact, email: e.target.value })}
                                                                    className="w-full px-2 py-1 border rounded text-sm"
                                                                    dir="ltr"
                                                                />
                                                            </td>
                                                            <td className="py-2 px-2">
                                                                <input
                                                                    type="tel"
                                                                    value={editingContact.whatsapp || ''}
                                                                    onChange={(e) => setEditingContact({ ...editingContact, whatsapp: e.target.value })}
                                                                    className="w-full px-2 py-1 border rounded text-sm"
                                                                    dir="ltr"
                                                                />
                                                            </td>
                                                            <td className="py-2 px-2 text-center">
                                                                {(() => {
                                                                    const meetingAvailability = parseMeetingAvailabilitySafely(editingContact.meeting_availability)
                                                                    return (
                                                                <button
                                                                    onClick={() => handleOpenAvailability(editingContact)}
                                                                    className={`inline-flex items-center gap-1 px-2 py-1 rounded-md text-sm transition-colors ${
                                                                        meetingAvailability
                                                                            ? 'text-primary-600 bg-primary-50 hover:bg-primary-100'
                                                                            : 'text-gray-400 hover:text-primary-600 hover:bg-gray-100'
                                                                    }`}
                                                                    title={t('Set meeting availability')}
                                                                >
                                                                    <CalendarClock className="w-4 h-4" />
                                                                    <span>{meetingAvailability ? t('Configured') : t('Set')}</span>
                                                                </button>
                                                                    )
                                                                })()}
                                                            </td>
                                                            <td className="py-2 px-2 text-center">
                                                                <div className="flex gap-1 justify-center">
                                                                    <button
                                                                        onClick={handleSaveContact}
                                                                        className="p-1 text-green-600 hover:bg-green-100 rounded"
                                                                        title={t('Save')}
                                                                    >
                                                                        <Save className="w-4 h-4" />
                                                                    </button>
                                                                    <button
                                                                        onClick={() => setEditingContact(null)}
                                                                        className="p-1 text-gray-400 hover:bg-gray-100 rounded"
                                                                        title={t('Cancel')}
                                                                    >
                                                                        <X className="w-4 h-4" />
                                                                    </button>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    ) : (
                                                        // Display mode row
                                                        <tr key={contact.id} className="border-b hover:bg-gray-50">
                                                            <td className="py-2 px-3 font-medium">{contact.name}</td>
                                                            <td className="py-2 px-3 text-gray-600">{contact.title || '-'}</td>
                                                            <td className="py-2 px-3 text-gray-600" dir="ltr">
                                                                {contact.phone && (
                                                                    <a href={`tel:${contact.phone}`} className="flex items-center gap-1 hover:text-primary-600">
                                                                        <Phone className="w-3 h-3" />
                                                                        {contact.phone}
                                                                    </a>
                                                                )}
                                                            </td>
                                                            <td className="py-2 px-3 text-gray-600" dir="ltr">
                                                                {contact.email && (
                                                                    <a href={`mailto:${contact.email}`} className="flex items-center gap-1 hover:text-primary-600">
                                                                        <Mail className="w-3 h-3" />
                                                                        {contact.email}
                                                                    </a>
                                                                )}
                                                            </td>
                                                            <td className="py-2 px-3 text-gray-600" dir="ltr">
                                                                {contact.whatsapp && (
                                                                    <a 
                                                                        href={`https://wa.me/${contact.whatsapp.replace(/[^0-9]/g, '')}`}
                                                                        target="_blank"
                                                                        rel="noopener noreferrer"
                                                                        className="flex items-center gap-1 hover:text-green-600"
                                                                    >
                                                                        <MessageCircle className="w-3 h-3" />
                                                                        {contact.whatsapp}
                                                                    </a>
                                                                )}
                                                            </td>
                                                            <td className="py-2 px-3 text-center">
                                                                {(() => {
                                                                    const meetingAvailability = parseMeetingAvailabilitySafely(contact.meeting_availability)
                                                                    return (
                                                                <button
                                                                    onClick={() => handleOpenAvailability(contact)}
                                                                    className={`inline-flex items-center gap-1 px-2 py-1 rounded-md text-sm transition-colors ${
                                                                        meetingAvailability
                                                                            ? 'text-primary-600 bg-primary-50 hover:bg-primary-100'
                                                                            : 'text-gray-400 hover:text-primary-600 hover:bg-gray-100'
                                                                    }`}
                                                                    title={t('Set meeting availability')}
                                                                >
                                                                    <CalendarClock className="w-4 h-4" />
                                                                    <span>{meetingAvailability ? t('Configured') : t('Set')}</span>
                                                                </button>
                                                                    )
                                                                })()}
                                                            </td>
                                                            <td className="py-2 px-3 text-center">
                                                                <div className="flex gap-1 justify-center">
                                                                    <button
                                                                        onClick={() => handleEditContact(contact)}
                                                                        className="p-1 text-gray-400 hover:text-blue-600 transition-colors"
                                                                        title={t('Edit')}
                                                                    >
                                                                        <Edit2 className="w-4 h-4" />
                                                                    </button>
                                                                    <button
                                                                        onClick={() => handleDeleteContact(list.id, contact.id, contact.name)}
                                                                        className="p-1 text-gray-400 hover:text-red-600 transition-colors"
                                                                        title={t('Delete')}
                                                                    >
                                                                        <Trash2 className="w-4 h-4" />
                                                                    </button>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    )
                                                ))}
                                            </tbody>
                                        </table>
                                    </div>
                                ) : (
                                    <div className="text-center py-8 text-gray-500">
                                        <Users className="w-12 h-12 mx-auto mb-3 opacity-50" />
                                        <p>{t('No contacts in this list')}</p>
                                        <p className="text-sm">{t('Add manually or import from CSV file')}</p>
                                    </div>
                                )}
                            </CardContent>
                        )}
                    </Card>
                ))}

                {/* Empty State */}
                {lists.length === 0 && (
                    <Card>
                        <CardContent className="text-center py-12">
                            <Users className="w-12 h-12 mx-auto mb-4 text-gray-300" />
                            <p className="text-gray-500 mb-4">{t('No contact lists yet')}</p>
                            <Button onClick={() => setShowNewListForm(true)}>
                                <Plus className="w-4 h-4 me-2" />
                                {t('Create First List')}
                            </Button>
                        </CardContent>
                    </Card>
                )}
            </div>

            {/* Availability Schedule Editor Modal */}
            {(() => {
                const editContact = availContactId ? contacts.find(c => Number(c.id) === availContactId) : null
                const currentContactMeetingAvailability = parseMeetingAvailabilitySafely(editContact?.meeting_availability)
                return (
                    <AvailabilityScheduleEditor
                        isOpen={!!availContactId || isNewContactAvailabilityOpen}
                        contactName={isNewContactAvailabilityOpen ? (newContact.name || t('New Contact')) : (editContact?.name || '')}
                        initialData={
                            isNewContactAvailabilityOpen
                                ? newContact.meeting_availability
                                : currentContactMeetingAvailability
                        }
                        onSave={handleSaveAvailability}
                        onClose={() => {
                            setAvailContactId(null)
                            setIsNewContactAvailabilityOpen(false)
                        }}
                        isSaving={isSavingAvailability}
                    />
                )
            })()}
        </div>
    )
}
