// ReferentiView - Gestione referenti (persone di riferimento esterne)
// Two-column split view: list on left, details on right

function ReferentiView({ onViewProject }) {
    const { user: currentUser, isAdmin } = useAuth();
    const toast = useToast();
    const [referenti, setReferenti] = React.useState([]);
    const [projects, setProjects] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [showCreateModal, setShowCreateModal] = React.useState(false);
    const [editingReferente, setEditingReferente] = React.useState(null);
    const [filterProject, setFilterProject] = React.useState('');
    const [searchQuery, setSearchQuery] = React.useState('');
    const [confirmDelete, setConfirmDelete] = React.useState(null);
    const [selectedReferente, setSelectedReferente] = React.useState(null);

    // Permission checks
    const canEdit = isAdmin || currentUser?.can_update_referenti;
    const canDelete = isAdmin || currentUser?.can_delete_referenti;
    const canCreate = isAdmin || currentUser?.can_create_referenti;

    // Create project lookup map for efficient access
    const projectsMap = React.useMemo(() => {
        const map = new Map();
        projects.forEach(p => map.set(p.id, p));
        return map;
    }, [projects]);

    // Helper to get full project objects for a referente
    const getReferenteProjects = React.useCallback((referente) => {
        if (!referente) return [];
        return (referente.project_ids || [])
            .map(id => projectsMap.get(id))
            .filter(Boolean);
    }, [projectsMap]);

    const loadData = async () => {
        setLoading(true);

        // Small delay to ensure backend has committed changes
        await new Promise(resolve => setTimeout(resolve, 100));

        try {
            const [referentiData, projectsData] = await Promise.all([
                ApiUtils.fetchReferenti(filterProject || null, false),
                ApiUtils.fetchProjects(true),
            ]);
            // Force new array references for React to detect changes
            const newReferenti = referentiData.map(r => ({ ...r, _key: Date.now() }));
            setReferenti(newReferenti);
            setProjects(projectsData.map(p => ({ ...p, _key: Date.now() })));

            // Update selected referente with fresh data if one is selected
            if (selectedReferente) {
                const updated = newReferenti.find(r => r.id === selectedReferente.id);
                if (updated) {
                    setSelectedReferente(updated);
                } else {
                    setSelectedReferente(null);
                }
            }
        } catch (err) {
            toast('Errore nel caricamento dati: ' + err.message, 'error');
        } finally {
            setLoading(false);
        }
    };

    React.useEffect(() => {
        loadData();
    }, [filterProject]);

    const handleDelete = (referente) => {
        setConfirmDelete({ id: referente.id, name: referente.full_name });
    };

    const executeDelete = async () => {
        if (!confirmDelete) return;

        try {
            await ApiUtils.deleteReferente(confirmDelete.id);
            toast('Referente eliminato con successo', 'success');
            setConfirmDelete(null);
            if (selectedReferente?.id === confirmDelete.id) {
                setSelectedReferente(null);
            }
            loadData();
        } catch (err) {
            toast('Errore nell\'eliminazione: ' + err.message, 'error');
            setConfirmDelete(null);
        }
    };

    const handleEdit = (referente) => {
        setEditingReferente(referente);
    };

    const handleNavigateToProject = (project) => {
        if (onViewProject) {
            onViewProject(project.id);
        }
    };

    // Filter referenti based on search query
    const filteredReferenti = React.useMemo(() => {
        if (!searchQuery.trim()) return referenti;

        const query = searchQuery.toLowerCase().trim();
        return referenti.filter(r =>
            r.full_name.toLowerCase().includes(query) ||
            (r.email && r.email.toLowerCase().includes(query)) ||
            (r.phone_number && r.phone_number.includes(query))
        );
    }, [referenti, searchQuery]);

    // Format date helper
    const formatDate = (dateStr) => {
        if (!dateStr) return '';
        try {
            return new Date(dateStr).toLocaleDateString('it-IT', {
                day: 'numeric',
                month: 'short',
                year: 'numeric'
            });
        } catch {
            return dateStr;
        }
    };

    // Get selected referente's projects
    const selectedProjects = getReferenteProjects(selectedReferente);

    // Calculate project progress (same as WelcomeView)
    const getProjectProgress = (project) => {
        if (!project.steps || project.steps.length === 0) return { completed: 0, total: 0, percent: 0 };
        const completed = project.steps.filter(s => s.status === 'completato').length;
        const total = project.steps.length;
        return { completed, total, percent: Math.round((completed / total) * 100) };
    };

    // Get project assignees
    const getProjectAssignees = (project) => {
        if (!project.assignments || project.assignments.length === 0) return [];
        return project.assignments.map(a => ({
            id: a.user_id,
            name: a.user_name || a.user_email,
            email: a.user_email
        }));
    };

    return (
        <div className="p-6 h-full flex flex-col">
            {/* Header */}
            <div className="flex items-center justify-between mb-6">
                <div>
                    <h2 className="text-2xl font-bold text-slate-800">Gestione Referenti</h2>
                    <p className="text-slate-500 mt-1">Persone di riferimento esterne per i progetti</p>
                </div>
                {canCreate && (
                    <button
                        onClick={() => setShowCreateModal(true)}
                        className="flex items-center gap-2 px-4 py-2 bg-brand-500 hover:bg-brand-600 text-white font-medium rounded-lg transition-colors"
                    >
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                        </svg>
                        Nuovo Referente
                    </button>
                )}
            </div>

            {/* Two Column Layout */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 flex-1 min-h-0">
                {/* Left Column - Referenti List */}
                <div className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden flex flex-col">
                    {/* List Header with Search & Filter */}
                    <div className="p-4 border-b border-slate-100 bg-slate-50 space-y-3">
                        <h3 className="font-semibold text-slate-800 flex items-center gap-2">
                            <svg className="w-5 h-5 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
                            </svg>
                            Elenco Referenti
                            <span className="ml-auto text-sm font-normal text-slate-500">
                                {filteredReferenti.length} {filteredReferenti.length === 1 ? 'referente' : 'referenti'}
                            </span>
                        </h3>

                        {/* Search */}
                        <div className="relative">
                            <svg className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                            </svg>
                            <input
                                type="text"
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                                placeholder="Cerca per nome, email o telefono..."
                                className="w-full pl-9 pr-3 py-2 text-sm border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                            />
                        </div>

                        {/* Project Filter */}
                        <select
                            value={filterProject}
                            onChange={(e) => setFilterProject(e.target.value)}
                            className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                        >
                            <option value="">Tutte le pratiche</option>
                            {projects.map(p => (
                                <option key={p.id} value={p.id}>{p.name}</option>
                            ))}
                        </select>
                    </div>

                    {/* Referenti List */}
                    <div className="flex-1 overflow-y-auto scrollbar-thin">
                        {loading ? (
                            <div className="p-8 text-center">
                                <Spinner size="lg" />
                                <p className="text-slate-500 mt-4">Caricamento referenti...</p>
                            </div>
                        ) : filteredReferenti.length === 0 ? (
                            <div className="p-8 text-center">
                                <svg className="w-12 h-12 text-slate-300 mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
                                </svg>
                                <p className="text-slate-500 text-sm">
                                    {searchQuery ? 'Nessun referente trovato' : 'Nessun referente'}
                                </p>
                                {canCreate && !searchQuery && (
                                    <button
                                        onClick={() => setShowCreateModal(true)}
                                        className="mt-3 text-sm text-brand-500 hover:text-brand-600 font-medium"
                                    >
                                        Aggiungi il primo referente
                                    </button>
                                )}
                            </div>
                        ) : (
                            <div className="divide-y divide-slate-100">
                                {filteredReferenti.map(referente => {
                                    const isSelected = selectedReferente?.id === referente.id;
                                    const refProjects = getReferenteProjects(referente);

                                    return (
                                        <div
                                            key={referente.id}
                                            onClick={() => setSelectedReferente(referente)}
                                            className={`p-4 cursor-pointer transition-colors ${
                                                isSelected
                                                    ? 'bg-brand-50 border-l-4 border-brand-500'
                                                    : 'hover:bg-slate-50 border-l-4 border-transparent'
                                            }`}
                                        >
                                            <div className="flex items-start gap-3">
                                                {/* Avatar */}
                                                <div className="w-10 h-10 bg-gradient-to-br from-teal-400 to-teal-600 rounded-full flex items-center justify-center text-white font-semibold text-sm flex-shrink-0">
                                                    {referente.first_name ? referente.first_name.charAt(0).toUpperCase() : ''}{referente.last_name?.charAt(0).toUpperCase()}
                                                </div>

                                                {/* Info */}
                                                <div className="flex-1 min-w-0">
                                                    <h4 className="font-medium text-slate-800 truncate">
                                                        {referente.full_name}
                                                    </h4>
                                                    {referente.email && (
                                                        <p className="text-sm text-slate-500 truncate">{referente.email}</p>
                                                    )}

                                                    {/* Project badges */}
                                                    {refProjects.length > 0 && (
                                                        <div className="flex flex-wrap gap-1 mt-2">
                                                            {refProjects.slice(0, 2).map(project => (
                                                                <ProjectStatusBadge
                                                                    key={project.id}
                                                                    status={project.status}
                                                                    projectName={project.name}
                                                                    showDot={true}
                                                                />
                                                            ))}
                                                            {refProjects.length > 2 && (
                                                                <span className="inline-flex items-center px-2 py-0.5 bg-slate-100 text-slate-600 rounded-full text-xs font-medium">
                                                                    +{refProjects.length - 2}
                                                                </span>
                                                            )}
                                                        </div>
                                                    )}
                                                </div>

                                                {/* Arrow indicator */}
                                                <svg
                                                    className={`w-5 h-5 flex-shrink-0 transition-colors ${
                                                        isSelected ? 'text-brand-500' : 'text-slate-300'
                                                    }`}
                                                    fill="none"
                                                    stroke="currentColor"
                                                    viewBox="0 0 24 24"
                                                >
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                                </svg>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        )}
                    </div>
                </div>

                {/* Right Column - Selected Referente Details */}
                <div className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden flex flex-col">
                    {selectedReferente ? (
                        <>
                            {/* Detail Header */}
                            <div className="p-5 border-b border-slate-100 bg-slate-50">
                                <h3 className="font-semibold text-slate-800 flex items-center gap-2">
                                    <svg className="w-5 h-5 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                                    </svg>
                                    Dettagli Referente
                                </h3>
                            </div>

                            {/* Detail Content */}
                            <div className="flex-1 overflow-y-auto scrollbar-thin p-5 space-y-6">
                                {/* Profile Section */}
                                <div className="flex items-start gap-4">
                                    <div className="w-16 h-16 bg-gradient-to-br from-teal-400 to-teal-600 rounded-full flex items-center justify-center text-white font-bold text-xl flex-shrink-0">
                                        {selectedReferente.first_name ? selectedReferente.first_name.charAt(0).toUpperCase() : ''}{selectedReferente.last_name?.charAt(0).toUpperCase()}
                                    </div>
                                    <div className="flex-1">
                                        <h3 className="text-xl font-semibold text-slate-900">
                                            {selectedReferente.full_name}
                                        </h3>

                                        {/* Contact Links */}
                                        <div className="mt-2 space-y-1">
                                            {selectedReferente.email && (
                                                <a
                                                    href={`mailto:${selectedReferente.email}`}
                                                    className="flex items-center gap-2 text-sm text-slate-600 hover:text-brand-600 transition-colors"
                                                >
                                                    <svg className="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                                                    </svg>
                                                    {selectedReferente.email}
                                                </a>
                                            )}
                                            {selectedReferente.phone_number && (
                                                <a
                                                    href={`tel:${selectedReferente.phone_number}`}
                                                    className="flex items-center gap-2 text-sm text-slate-600 hover:text-brand-600 transition-colors"
                                                >
                                                    <svg className="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                                                    </svg>
                                                    {selectedReferente.phone_number}
                                                </a>
                                            )}
                                        </div>

                                        {selectedReferente.created_at && (
                                            <p className="mt-2 text-xs text-slate-400">
                                                Aggiunto il {formatDate(selectedReferente.created_at)}
                                            </p>
                                        )}
                                    </div>
                                </div>

                                {/* Notes Section */}
                                {selectedReferente.notes && (
                                    <div className="border-t border-slate-100 pt-5">
                                        <h4 className="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">
                                            Note
                                        </h4>
                                        <p className="text-sm text-slate-600 whitespace-pre-wrap bg-slate-50 rounded-lg p-3 border border-slate-100">
                                            {selectedReferente.notes}
                                        </p>
                                    </div>
                                )}

                                {/* Projects Section */}
                                <div className="border-t border-slate-100 pt-5">
                                    <h4 className="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-3">
                                        Pratiche Associate ({selectedProjects.length})
                                    </h4>

                                    {selectedProjects.length > 0 ? (
                                        <div className="space-y-3">
                                            {selectedProjects.map(project => {
                                                const progress = getProjectProgress(project);
                                                const assignees = getProjectAssignees(project);

                                                return (
                                                    <div
                                                        key={project.id}
                                                        onClick={() => handleNavigateToProject(project)}
                                                        className="p-3 bg-slate-50 hover:bg-slate-100 rounded-lg transition-colors cursor-pointer group border border-slate-100"
                                                    >
                                                        {/* Project Header */}
                                                        <div className="flex items-start justify-between gap-2 mb-2">
                                                            <div className="flex-1 min-w-0">
                                                                <p className="font-medium text-slate-900 truncate">
                                                                    {project.name}
                                                                </p>
                                                                <p className="text-xs text-slate-500">
                                                                    {getProjectStatusConfig(project.status).label}
                                                                    {project.due_date && (
                                                                        <span className="ml-2">
                                                                            • Scadenza: {formatDate(project.due_date)}
                                                                        </span>
                                                                    )}
                                                                </p>
                                                            </div>
                                                            <svg
                                                                className="w-4 h-4 text-slate-400 group-hover:text-slate-600 transition-colors flex-shrink-0 mt-1"
                                                                fill="none"
                                                                stroke="currentColor"
                                                                viewBox="0 0 24 24"
                                                            >
                                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                                            </svg>
                                                        </div>

                                                        {/* Progress Bar */}
                                                        <div className="flex items-center gap-2 mb-2">
                                                            <div className="flex-1 h-2 bg-slate-200 rounded-full overflow-hidden">
                                                                <div
                                                                    className={`h-full rounded-full transition-all ${
                                                                        progress.percent === 100
                                                                            ? 'bg-emerald-500'
                                                                            : progress.percent >= 50
                                                                                ? 'bg-brand-500'
                                                                                : progress.percent > 0
                                                                                    ? 'bg-amber-500'
                                                                                    : 'bg-slate-300'
                                                                    }`}
                                                                    style={{ width: `${progress.percent}%` }}
                                                                />
                                                            </div>
                                                            <span className="text-xs font-medium text-slate-600 w-10 text-right">
                                                                {progress.percent}%
                                                            </span>
                                                        </div>

                                                        {/* Steps count */}
                                                        <div className="flex items-center justify-between text-xs text-slate-500">
                                                            <span>{progress.completed}/{progress.total} completati</span>
                                                        </div>

                                                        {/* Assigned Users */}
                                                        {assignees.length > 0 && (
                                                            <div className="mt-2 flex items-center gap-2 pt-2 border-t border-slate-200">
                                                                <div className="flex -space-x-2">
                                                                    {assignees.slice(0, 3).map((user) => (
                                                                        <div
                                                                            key={user.id}
                                                                            className="w-6 h-6 rounded-full bg-brand-100 border-2 border-white flex items-center justify-center"
                                                                            title={user.name || user.email}
                                                                        >
                                                                            <span className="text-xs font-semibold text-brand-600">
                                                                                {(user.name || user.email || '?').charAt(0).toUpperCase()}
                                                                            </span>
                                                                        </div>
                                                                    ))}
                                                                    {assignees.length > 3 && (
                                                                        <div className="w-6 h-6 rounded-full bg-slate-100 border-2 border-white flex items-center justify-center">
                                                                            <span className="text-xs font-semibold text-slate-600">
                                                                                +{assignees.length - 3}
                                                                            </span>
                                                                        </div>
                                                                    )}
                                                                </div>
                                                                <span className="text-xs text-slate-400">
                                                                    {assignees.length === 1 ? '1 assegnato' : `${assignees.length} assegnati`}
                                                                </span>
                                                            </div>
                                                        )}
                                                    </div>
                                                );
                                            })}
                                        </div>
                                    ) : (
                                        <div className="text-center py-6 bg-slate-50 rounded-lg border border-slate-100">
                                            <svg className="w-10 h-10 mx-auto text-slate-200 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                            </svg>
                                            <p className="text-sm text-slate-400">Nessuna pratica associata</p>
                                        </div>
                                    )}
                                </div>
                            </div>

                            {/* Action Buttons */}
                            {(canEdit || canDelete) && (
                                <div className="p-4 border-t border-slate-200 bg-slate-50 flex gap-3">
                                    {canEdit && (
                                        <button
                                            onClick={() => handleEdit(selectedReferente)}
                                            className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-white border border-slate-200 text-slate-700 rounded-lg hover:bg-slate-50 transition-colors font-medium"
                                        >
                                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
                                            </svg>
                                            Modifica
                                        </button>
                                    )}
                                    {canDelete && (
                                        <button
                                            onClick={() => handleDelete(selectedReferente)}
                                            className="flex items-center justify-center gap-2 px-4 py-2.5 text-red-600 hover:bg-red-50 border border-red-200 rounded-lg transition-colors font-medium"
                                        >
                                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                            </svg>
                                            Elimina
                                        </button>
                                    )}
                                </div>
                            )}
                        </>
                    ) : (
                        /* Empty State - No Selection */
                        <div className="flex-1 flex items-center justify-center p-8">
                            <div className="text-center">
                                <div className="w-20 h-20 mx-auto mb-4 bg-slate-100 rounded-full flex items-center justify-center">
                                    <svg className="w-10 h-10 text-slate-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                                    </svg>
                                </div>
                                <h3 className="text-lg font-medium text-slate-700 mb-1">
                                    Seleziona un referente
                                </h3>
                                <p className="text-sm text-slate-500">
                                    Scegli un referente dalla lista per visualizzare i dettagli e le pratiche associate
                                </p>
                            </div>
                        </div>
                    )}
                </div>
            </div>

            {/* Create Referente Modal */}
            {showCreateModal && (
                <ReferenteModal
                    projects={projects}
                    onClose={() => setShowCreateModal(false)}
                    onSuccess={() => {
                        setShowCreateModal(false);
                        loadData();
                        toast('Referente creato con successo', 'success');
                    }}
                />
            )}

            {/* Edit Referente Modal */}
            {editingReferente && (
                <ReferenteModal
                    referente={editingReferente}
                    projects={projects}
                    onClose={() => setEditingReferente(null)}
                    onSuccess={() => {
                        setEditingReferente(null);
                        loadData();
                        toast('Referente aggiornato con successo', 'success');
                    }}
                />
            )}

            {/* Confirmation Modal */}
            {confirmDelete && (
                <ConfirmationModal
                    title="Elimina Referente"
                    message={`Sei sicuro di voler eliminare definitivamente il referente "${confirmDelete.name}"?\n\nQuesta azione non può essere annullata.`}
                    confirmText="Elimina"
                    variant="danger"
                    onConfirm={executeDelete}
                    onCancel={() => setConfirmDelete(null)}
                />
            )}
        </div>
    );
}

// Referente Modal Component (Create/Edit)
function ReferenteModal({ referente = null, projects, onClose, onSuccess }) {
    const isEditing = !!referente;
    const [formData, setFormData] = React.useState({
        first_name: referente?.first_name || '',
        last_name: referente?.last_name || '',
        phone_number: referente?.phone_number || '',
        email: referente?.email || '',
        notes: referente?.notes || '',
        project_ids: referente?.project_ids || [],
    });
    const [loading, setLoading] = React.useState(false);
    const [error, setError] = React.useState('');

    const handleProjectToggle = (projectId) => {
        setFormData(prev => ({
            ...prev,
            project_ids: prev.project_ids.includes(projectId)
                ? prev.project_ids.filter(id => id !== projectId)
                : [...prev.project_ids, projectId]
        }));
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setError('');
        setLoading(true);

        try {
            const data = { ...formData };
            // Clean up empty optional fields
            if (!data.phone_number) delete data.phone_number;
            if (!data.email) delete data.email;
            if (!data.notes) delete data.notes;

            if (isEditing) {
                await ApiUtils.updateReferente(referente.id, data);
            } else {
                await ApiUtils.createReferente(data);
            }

            onSuccess();
        } catch (err) {
            setError(err.message);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-xl shadow-xl max-w-lg w-full max-h-[90vh] overflow-y-auto">
                <div className="flex items-center justify-between p-6 border-b border-slate-200 sticky top-0 bg-white">
                    <h3 className="text-lg font-semibold text-slate-800">
                        {isEditing ? 'Modifica Referente' : 'Nuovo Referente'}
                    </h3>
                    <button onClick={onClose} className="text-slate-400 hover:text-slate-600">
                        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>

                <form onSubmit={handleSubmit} className="p-6 space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium text-slate-700 mb-1">
                                Nome
                                <span className="text-slate-400 font-normal ml-1">(opzionale)</span>
                            </label>
                            <input
                                type="text"
                                value={formData.first_name}
                                onChange={(e) => setFormData({ ...formData, first_name: e.target.value })}
                                className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                                placeholder="Mario"
                            />
                        </div>

                        <div>
                            <label className="block text-sm font-medium text-slate-700 mb-1">Cognome *</label>
                            <input
                                type="text"
                                value={formData.last_name}
                                onChange={(e) => setFormData({ ...formData, last_name: e.target.value })}
                                className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                                required
                                placeholder="Rossi"
                            />
                        </div>

                        <div>
                            <label className="block text-sm font-medium text-slate-700 mb-1">
                                Telefono
                                <span className="text-slate-400 font-normal ml-1">(opzionale)</span>
                            </label>
                            <input
                                type="tel"
                                value={formData.phone_number}
                                onChange={(e) => setFormData({ ...formData, phone_number: e.target.value })}
                                className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                                placeholder="+39 123 456 7890"
                            />
                        </div>

                        <div>
                            <label className="block text-sm font-medium text-slate-700 mb-1">
                                Email
                                <span className="text-slate-400 font-normal ml-1">(opzionale)</span>
                            </label>
                            <input
                                type="email"
                                value={formData.email}
                                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                                className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                                placeholder="mario.rossi@email.com"
                            />
                        </div>

                        <div className="col-span-2">
                            <label className="block text-sm font-medium text-slate-700 mb-1">
                                Note
                                <span className="text-slate-400 font-normal ml-1">(opzionale)</span>
                            </label>
                            <textarea
                                value={formData.notes}
                                onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                                className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                                rows={3}
                                placeholder="Aggiungi note o informazioni aggiuntive..."
                            />
                        </div>
                    </div>

                    {/* Project Selection */}
                    {projects && projects.length > 0 && (
                        <div className="border-t border-slate-200 pt-4 mt-4">
                            <label className="block text-sm font-medium text-slate-700 mb-3">
                                Pratiche Associate
                                <span className="text-slate-400 font-normal ml-1">(opzionale - seleziona uno o più)</span>
                            </label>
                            <div className="space-y-2 max-h-48 overflow-y-auto border border-slate-200 rounded-lg p-3">
                                {projects.map(project => {
                                    const isSelected = formData.project_ids.includes(project.id);
                                    const statusConfig = getProjectStatusConfig(project.status);
                                    return (
                                        <label
                                            key={project.id}
                                            className={`flex items-center gap-3 p-2 rounded-lg cursor-pointer transition-colors ${
                                                isSelected ? 'bg-brand-50 border border-brand-200' : 'hover:bg-slate-50 border border-transparent'
                                            }`}
                                        >
                                            <input
                                                type="checkbox"
                                                checked={isSelected}
                                                onChange={() => handleProjectToggle(project.id)}
                                                className="w-4 h-4 text-brand-500 rounded focus:ring-brand-500"
                                            />
                                            <ProjectStatusDot status={project.status} size="sm" />
                                            <div className="flex-1 min-w-0">
                                                <div className="text-sm font-medium text-slate-800">{project.name}</div>
                                                <div className="text-xs text-slate-500">{statusConfig.label}</div>
                                            </div>
                                        </label>
                                    );
                                })}
                            </div>
                            {formData.project_ids.length > 0 && (
                                <p className="text-xs text-slate-500 mt-2">
                                    {formData.project_ids.length} pratica/che selezionata/e
                                </p>
                            )}
                        </div>
                    )}

                    {error && (
                        <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-600">
                            {error}
                        </div>
                    )}

                    <div className="flex gap-3 pt-4">
                        <button
                            type="button"
                            onClick={onClose}
                            className="flex-1 px-4 py-2 border border-slate-200 text-slate-600 font-medium rounded-lg hover:bg-slate-50 transition-colors"
                        >
                            Annulla
                        </button>
                        <button
                            type="submit"
                            disabled={loading}
                            className="flex-1 px-4 py-2 bg-brand-500 text-white font-medium rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-50"
                        >
                            {loading ? 'Salvataggio...' : (isEditing ? 'Salva Modifiche' : 'Crea Referente')}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
}

window.ReferentiView = ReferentiView;
