// TeamOverviewWidget - Shows team performance metrics for admin
function TeamOverviewWidget({ projects, isAdmin }) {
    const { user } = useAuth();
    const [activeTab, setActiveTab] = React.useState('ranking'); // 'ranking', 'reasons'
    const [expanded, setExpanded] = React.useState(false);

    // Aggregate team performance data from projects
    const { teamData, cancellationReasons, projectTotals } = React.useMemo(() => {
        const userMap = new Map();
        const reasonsMap = new Map();

        // Track unique project counts for summary
        const totals = { completed: 0, cancelled: 0, onTime: 0, late: 0 };

        projects.forEach(project => {
            // Determine project outcome once per project (for totals)
            const isCompleted = project.status === 'completed' || (project.is_archived && !project.is_cancelled);

            if (project.is_cancelled) {
                totals.cancelled++;
            } else if (isCompleted) {
                totals.completed++;
                // Check if completed on time
                if (project.due_date) {
                    const dueDate = new Date(project.due_date);
                    const completedDate = project.archived_at
                        ? new Date(project.archived_at)
                        : (project.updated_at ? new Date(project.updated_at) : new Date());
                    dueDate.setHours(23, 59, 59, 999);
                    if (completedDate <= dueDate) {
                        totals.onTime++;
                    } else {
                        totals.late++;
                    }
                } else {
                    totals.onTime++;
                }
            }

            // Track cancellation reasons
            if (project.is_cancelled && project.cancellation_reason) {
                const reason = project.cancellation_reason.trim();
                if (reason) {
                    reasonsMap.set(reason, (reasonsMap.get(reason) || 0) + 1);
                }
            }

            // Get assignments based on what's available
            const assignments = project.assignments || [];

            // For regular users, also add their own assignment if present
            if (!isAdmin && project.my_assignment) {
                const hasCurrentUser = assignments.some(a => a.user_id === user?.id);
                if (!hasCurrentUser && user) {
                    assignments.push({
                        user_id: user.id,
                        user_name: user.full_name,
                        user_email: user.email
                    });
                }
            }

            assignments.forEach(assignment => {
                const userId = assignment.user_id;
                if (!userId) return;

                if (!userMap.has(userId)) {
                    userMap.set(userId, {
                        id: userId,
                        name: assignment.user_name || assignment.user_email || 'Utente',
                        email: assignment.user_email,
                        avatar: assignment.user_avatar,
                        totalProjects: 0,
                        activeProjects: 0,
                        completedProjects: 0,
                        cancelledProjects: 0,
                        completedOnTime: 0,
                        completedLate: 0,
                        isCurrentUser: userId === user?.id
                    });
                }

                const userData = userMap.get(userId);
                userData.totalProjects++;

                if (project.is_cancelled) {
                    userData.cancelledProjects++;
                } else if (isCompleted) {
                    userData.completedProjects++;
                    // Check if completed on time (before or on due_date)
                    if (project.due_date) {
                        const dueDate = new Date(project.due_date);
                        // Use archived_at for completion time if available, otherwise updated_at
                        const completedDate = project.archived_at
                            ? new Date(project.archived_at)
                            : (project.updated_at ? new Date(project.updated_at) : new Date());
                        // Compare only dates, not times
                        dueDate.setHours(23, 59, 59, 999);
                        if (completedDate <= dueDate) {
                            userData.completedOnTime++;
                        } else {
                            userData.completedLate++;
                        }
                    } else {
                        // No due date = considered on time
                        userData.completedOnTime++;
                    }
                } else {
                    userData.activeProjects++;
                }
            });
        });

        // Sort by completed on time (descending), then by total completed
        const sortedTeam = Array.from(userMap.values()).sort((a, b) => {
            // Primary: completed on time
            if (b.completedOnTime !== a.completedOnTime) {
                return b.completedOnTime - a.completedOnTime;
            }
            // Secondary: total completed
            if (b.completedProjects !== a.completedProjects) {
                return b.completedProjects - a.completedProjects;
            }
            // Tertiary: fewer cancelled is better
            return a.cancelledProjects - b.cancelledProjects;
        });

        // Sort cancellation reasons by count
        const sortedReasons = Array.from(reasonsMap.entries())
            .map(([reason, count]) => ({ reason, count }))
            .sort((a, b) => b.count - a.count);

        return { teamData: sortedTeam, cancellationReasons: sortedReasons, projectTotals: totals };
    }, [projects, user, isAdmin]);

    // Get initials from name
    const getInitials = (name) => {
        if (!name) return '?';
        const parts = name.split(' ').filter(Boolean);
        if (parts.length >= 2) {
            return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
        }
        return name.substring(0, 2).toUpperCase();
    };

    // Get avatar color based on name
    const getAvatarColor = (name) => {
        const colors = [
            'bg-blue-500', 'bg-green-500', 'bg-amber-500', 'bg-red-500',
            'bg-purple-500', 'bg-pink-500', 'bg-indigo-500', 'bg-teal-500'
        ];
        const hash = name?.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0) || 0;
        return colors[hash % colors.length];
    };

    const visibleMembers = expanded ? teamData : teamData.slice(0, 5);
    const hasMore = teamData.length > 5;

    if (teamData.length === 0) {
        return (
            <Card className="p-4">
                <h3 className="font-semibold text-slate-900 flex items-center gap-2 mb-4">
                    <svg className="w-5 h-5 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                              d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                    </svg>
                    Statistiche Team
                </h3>
                <p className="text-sm text-slate-500 text-center py-4">Nessun dato disponibile</p>
            </Card>
        );
    }

    return (
        <Card className="p-4">
            {/* Header */}
            <div className="flex items-center justify-between mb-4">
                <h3 className="font-semibold text-slate-900 flex items-center gap-2">
                    <svg className="w-5 h-5 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                              d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                    </svg>
                    Statistiche Team
                </h3>
            </div>

            {/* Summary Stats */}
            <div className="grid grid-cols-2 gap-2 mb-4">
                <div className="bg-green-50 rounded-lg p-2.5 text-center">
                    <div className="text-lg font-bold text-green-600">{projectTotals.completed}</div>
                    <div className="text-xs text-green-700">Completate</div>
                </div>
                <div className="bg-red-50 rounded-lg p-2.5 text-center">
                    <div className="text-lg font-bold text-red-600">{projectTotals.cancelled}</div>
                    <div className="text-xs text-red-700">Annullate</div>
                </div>
            </div>

            {/* Tabs */}
            <div className="flex gap-1 mb-3 bg-slate-100 rounded-lg p-1">
                <button
                    onClick={() => setActiveTab('ranking')}
                    className={`flex-1 py-1.5 px-2 text-xs font-medium rounded-md transition-colors
                               ${activeTab === 'ranking'
                                   ? 'bg-white text-slate-900 shadow-sm'
                                   : 'text-slate-600 hover:text-slate-900'}`}
                >
                    Classifica
                </button>
                <button
                    onClick={() => setActiveTab('reasons')}
                    className={`flex-1 py-1.5 px-2 text-xs font-medium rounded-md transition-colors
                               ${activeTab === 'reasons'
                                   ? 'bg-white text-slate-900 shadow-sm'
                                   : 'text-slate-600 hover:text-slate-900'}`}
                >
                    Motivi Annullamento
                </button>
            </div>

            {/* Ranking Tab */}
            {activeTab === 'ranking' && (
                <>
                    <div className="space-y-2">
                        {visibleMembers.map((member, index) => {
                            const successRate = member.completedProjects > 0
                                ? Math.round((member.completedOnTime / member.completedProjects) * 100)
                                : 0;

                            return (
                                <div
                                    key={member.id}
                                    className={`flex items-center gap-2 p-2 rounded-lg transition-colors
                                               ${member.isCurrentUser ? 'bg-brand-50 border border-brand-100' : 'hover:bg-slate-50'}`}
                                >
                                    {/* Rank */}
                                    <div className="w-6 flex-shrink-0 text-center">
                                        <span className="text-xs font-medium text-slate-400">#{index + 1}</span>
                                    </div>

                                    {/* Avatar */}
                                    {member.avatar ? (
                                        <img
                                            src={window.ApiUsers?.getAvatarUrl(member.avatar)}
                                            alt={member.name}
                                            className="w-8 h-8 rounded-full object-cover flex-shrink-0"
                                        />
                                    ) : (
                                        <div className={`w-8 h-8 rounded-full flex items-center justify-center
                                                        text-white text-xs font-medium flex-shrink-0 ${getAvatarColor(member.name)}`}>
                                            {getInitials(member.name)}
                                        </div>
                                    )}

                                    {/* Info */}
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-center gap-1.5">
                                            <span className="text-sm font-medium text-slate-800 truncate">
                                                {member.name}
                                            </span>
                                            {member.isCurrentUser && (
                                                <span className="text-xs px-1 py-0.5 rounded bg-brand-100 text-brand-700">
                                                    Tu
                                                </span>
                                            )}
                                        </div>
                                        <div className="flex items-center gap-2 text-xs">
                                            <span className="text-green-600" title="Completate">
                                                {member.completedProjects} ✓
                                            </span>
                                            <span className="text-red-500" title="Annullate">
                                                {member.cancelledProjects} ✗
                                            </span>
                                            <span className="text-slate-400">|</span>
                                            <span className="text-blue-600" title="In tempo">
                                                {member.completedOnTime} puntuali
                                            </span>
                                        </div>
                                    </div>

                                    {/* Success rate */}
                                    {member.completedProjects > 0 && (
                                        <div className="text-right flex-shrink-0">
                                            <div className={`text-sm font-bold ${
                                                successRate >= 80 ? 'text-green-600' :
                                                successRate >= 50 ? 'text-amber-600' : 'text-red-500'
                                            }`}>
                                                {successRate}%
                                            </div>
                                            <div className="text-xs text-slate-400">puntualità</div>
                                        </div>
                                    )}
                                </div>
                            );
                        })}
                    </div>

                    {hasMore && (
                        <button
                            onClick={() => setExpanded(!expanded)}
                            className="w-full mt-3 py-2 text-sm text-brand-600 hover:text-brand-700
                                      font-medium rounded-lg hover:bg-brand-50 transition-colors"
                        >
                            {expanded ? 'Mostra meno' : `Mostra tutti (${teamData.length})`}
                        </button>
                    )}
                </>
            )}

            {/* Cancellation Reasons Tab */}
            {activeTab === 'reasons' && (
                <div className="space-y-2">
                    {cancellationReasons.length === 0 ? (
                        <p className="text-sm text-slate-500 text-center py-4">
                            Nessuna pratica annullata con motivo specificato
                        </p>
                    ) : (
                        cancellationReasons.slice(0, 5).map((item, index) => (
                            <div
                                key={index}
                                className="flex items-start gap-3 p-2.5 rounded-lg bg-slate-50"
                            >
                                <div className="flex-shrink-0 w-6 h-6 rounded-full bg-red-100 flex items-center justify-center">
                                    <span className="text-xs font-bold text-red-600">{item.count}</span>
                                </div>
                                <p className="text-sm text-slate-700 flex-1 line-clamp-2">
                                    {item.reason}
                                </p>
                            </div>
                        ))
                    )}
                    {cancellationReasons.length > 5 && (
                        <p className="text-xs text-slate-400 text-center pt-1">
                            +{cancellationReasons.length - 5} altri motivi
                        </p>
                    )}
                </div>
            )}
        </Card>
    );
}

window.TeamOverviewWidget = TeamOverviewWidget;
