// ActivityHeatmapWidget - Mappa di calore delle attività in stile GitHub
function ActivityHeatmapWidget({ notifications, projects, onViewProject }) {
    const [tooltip, setTooltip] = React.useState(null);
    const [selectedDate, setSelectedDate] = React.useState(null);

    // Abbreviazioni mesi in italiano
    const monthNames = ['Gen', 'Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Lug', 'Ago', 'Set', 'Ott', 'Nov', 'Dic'];

    // Helper per formattare la data in formato locale YYYY-MM-DD
    const formatLocalDate = (date) => {
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    };

    // Aggrega i dati delle attività per data (con dettagli)
    const { activityData, activityDetails } = React.useMemo(() => {
        const activityMap = new Map();
        const detailsMap = new Map();

        // Helper per aggiungere attività
        const addActivity = (date, activity) => {
            activityMap.set(date, (activityMap.get(date) || 0) + 1);
            if (!detailsMap.has(date)) {
                detailsMap.set(date, []);
            }
            detailsMap.get(date).push(activity);
        };

        // Conta le notifiche
        notifications.forEach(n => {
            if (n.created_at) {
                const date = formatLocalDate(n.created_at);
                addActivity(date, {
                    type: 'notification',
                    subtype: n.type,
                    title: n.title,
                    message: n.message,
                    time: n.created_at,
                    projectId: n.data?.project_id,
                    projectName: n.data?.project_name
                });
            }
        });

        // Conta gli aggiornamenti dei progetti
        projects.forEach(p => {
            if (p.updated_at) {
                const date = formatLocalDate(p.updated_at);
                addActivity(date, {
                    type: 'project_update',
                    title: `Pratica aggiornata`,
                    message: p.name,
                    time: p.updated_at,
                    projectId: p.id,
                    projectName: p.name
                });
            }
            if (p.created_at && formatLocalDate(p.created_at) !== formatLocalDate(p.updated_at)) {
                const date = formatLocalDate(p.created_at);
                addActivity(date, {
                    type: 'project_create',
                    title: `Pratica creata`,
                    message: p.name,
                    time: p.created_at,
                    projectId: p.id,
                    projectName: p.name
                });
            }
        });

        return { activityData: activityMap, activityDetails: detailsMap };
    }, [notifications, projects]);

    // Ottieni le attività dettagliate per una data specifica
    const getActivitiesForDate = React.useCallback((dateStr) => {
        const activities = activityDetails.get(dateStr) || [];
        // Ordina per ora (più recenti prima)
        return activities.sort((a, b) => new Date(b.time) - new Date(a.time));
    }, [activityDetails]);

    // Attività per la data selezionata
    const selectedActivities = React.useMemo(() => {
        if (!selectedDate) return [];
        return getActivitiesForDate(selectedDate);
    }, [selectedDate, getActivitiesForDate]);

    // Genera i dati della griglia per l'anno corrente (2026)
    const heatmapData = React.useMemo(() => {
        const weeks = [];
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        const todayStr = formatLocalDate(today);
        const currentYear = today.getFullYear();

        // Inizia dal 1 gennaio dell'anno corrente
        const jan1 = new Date(currentYear, 0, 1);
        const jan1DayOfWeek = jan1.getDay(); // 0=Dom, 1=Lun, ecc.

        // Termina il 31 dicembre dell'anno corrente
        const endDate = new Date(currentYear, 11, 31);

        // Prima settimana: riempi con slot vuoti prima del 1 gennaio
        let currentWeek = [];
        for (let i = 0; i < jan1DayOfWeek; i++) {
            currentWeek.push({
                date: null,
                count: 0,
                isEmpty: true,
                dayOfWeek: i,
                month: -1
            });
        }

        let currentDate = new Date(jan1);

        while (currentDate <= endDate) {
            const dateStr = formatLocalDate(currentDate);
            const isFuture = currentDate > today;
            currentWeek.push({
                date: dateStr,
                count: isFuture ? 0 : (activityData.get(dateStr) || 0),
                isToday: dateStr === todayStr,
                isFuture,
                isEmpty: false,
                dayOfWeek: currentDate.getDay(),
                month: currentDate.getMonth()
            });

            if (currentWeek.length === 7) {
                weeks.push(currentWeek);
                currentWeek = [];
            }

            currentDate.setDate(currentDate.getDate() + 1);
        }

        // Aggiungi i giorni rimanenti dell'ultima settimana, con padding per completare a 7 giorni
        if (currentWeek.length > 0) {
            while (currentWeek.length < 7) {
                currentWeek.push({
                    date: null,
                    count: 0,
                    isEmpty: true,
                    dayOfWeek: currentWeek.length,
                    month: -1
                });
            }
            weeks.push(currentWeek);
        }

        return weeks;
    }, [activityData]);

    // Calcola le posizioni delle etichette dei mesi
    const monthLabels = React.useMemo(() => {
        const labels = [];
        let lastMonth = -1;

        heatmapData.forEach((week, weekIndex) => {
            // Trova il primo giorno non vuoto della settimana
            const firstValidDay = week.find(day => !day.isEmpty);
            if (firstValidDay && firstValidDay.month !== lastMonth && firstValidDay.month >= 0) {
                labels.push({
                    month: firstValidDay.month,
                    weekIndex
                });
                lastMonth = firstValidDay.month;
            }
        });

        return labels;
    }, [heatmapData]);

    // Ottieni il colore in base al conteggio
    const getIntensityColor = (day) => {
        if (day.isEmpty) return 'bg-transparent';
        if (day.isFuture) return 'bg-slate-50';
        if (day.count === 0) return 'bg-slate-100';
        if (day.count <= 2) return 'bg-green-200';
        if (day.count <= 5) return 'bg-green-400';
        if (day.count <= 10) return 'bg-green-500';
        return 'bg-green-700';
    };

    // Calcola il totale delle attività
    const totalActivity = React.useMemo(() => {
        let total = 0;
        activityData.forEach(count => total += count);
        return total;
    }, [activityData]);

    // Formatta la data per il tooltip
    const formatTooltipDate = (dateStr) => {
        // Parse YYYY-MM-DD formato locale
        const [year, month, day] = dateStr.split('-').map(Number);
        return `${day} ${monthNames[month - 1]} ${year}`;
    };

    return (
        <Card className="p-4">
            <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-green-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>
                    Attività
                </h3>
                <span className="text-sm text-slate-500">
                    {totalActivity} attività nel {new Date().getFullYear()}
                </span>
            </div>

            {/* Etichette dei mesi */}
            <div className="relative h-5 mb-2 ml-8">
                {monthLabels.map((label, i) => (
                    <span
                        key={i}
                        className="absolute text-xs text-slate-400"
                        style={{ left: `${label.weekIndex * 14}px` }}
                    >
                        {monthNames[label.month]}
                    </span>
                ))}
            </div>

            {/* Griglia della mappa di calore */}
            <div className="flex gap-1 overflow-x-auto pb-2">
                {/* Etichette dei giorni */}
                <div className="flex flex-col gap-[2px] text-xs text-slate-400 pr-1 shrink-0">
                    <span className="h-3"></span>
                    <span className="h-3">Lun</span>
                    <span className="h-3"></span>
                    <span className="h-3">Mer</span>
                    <span className="h-3"></span>
                    <span className="h-3">Ven</span>
                    <span className="h-3"></span>
                </div>

                {/* Settimane */}
                <div className="flex gap-[2px]">
                    {heatmapData.map((week, weekIndex) => (
                        <div key={weekIndex} className="flex flex-col gap-[2px]">
                            {week.map((day, dayIndex) => (
                                <div
                                    key={dayIndex}
                                    className={`w-3 h-3 rounded-sm transition-colors
                                               ${getIntensityColor(day)}
                                               ${day.isToday ? 'ring-2 ring-brand-500' : ''}
                                               ${selectedDate && day.date && selectedDate === day.date ? 'ring-2 ring-blue-500' : ''}
                                               ${day.isEmpty || day.isFuture ? 'cursor-default' : 'cursor-pointer hover:ring-1 hover:ring-slate-500'}`}
                                    onMouseEnter={(e) => {
                                        if (day.isEmpty || day.isFuture) return;
                                        const rect = e.target.getBoundingClientRect();
                                        const activities = getActivitiesForDate(day.date);
                                        setTooltip({
                                            x: rect.left + rect.width / 2,
                                            y: rect.top - 8,
                                            date: day.date,
                                            count: day.count,
                                            activities: activities.slice(0, 3) // Preview first 3
                                        });
                                    }}
                                    onMouseLeave={() => setTooltip(null)}
                                    onClick={() => {
                                        if (day.isEmpty || day.isFuture) return;
                                        setSelectedDate(selectedDate === day.date ? null : day.date);
                                    }}
                                />
                            ))}
                        </div>
                    ))}
                </div>
            </div>

            {/* Legenda */}
            <div className="flex items-center justify-end gap-2 mt-2 text-xs text-slate-500">
                <span>Meno</span>
                <div className="flex gap-[2px]">
                    <div className="w-3 h-3 rounded-sm bg-slate-100" />
                    <div className="w-3 h-3 rounded-sm bg-green-200" />
                    <div className="w-3 h-3 rounded-sm bg-green-400" />
                    <div className="w-3 h-3 rounded-sm bg-green-500" />
                    <div className="w-3 h-3 rounded-sm bg-green-700" />
                </div>
                <span>Più</span>
            </div>

            {/* Suggerimento migliorato */}
            {tooltip && (
                <div
                    className="fixed z-50 px-3 py-2 bg-slate-800 text-white text-xs rounded-lg shadow-lg
                              pointer-events-none transform -translate-x-1/2 -translate-y-full min-w-[180px] max-w-[250px]"
                    style={{ left: tooltip.x, top: tooltip.y }}
                >
                    <div className="font-semibold text-sm mb-1">
                        {formatTooltipDate(tooltip.date)}
                    </div>
                    <div className="text-slate-300 mb-2">
                        {tooltip.count === 0
                            ? 'Nessuna attività'
                            : `${tooltip.count} ${tooltip.count === 1 ? 'attività' : 'attività'}`}
                    </div>
                    {tooltip.activities && tooltip.activities.length > 0 && (
                        <div className="border-t border-slate-600 pt-2 space-y-1">
                            {tooltip.activities.map((activity, i) => (
                                <div key={i} className="text-slate-200 truncate">
                                    <span className="text-slate-400">•</span> {activity.title}
                                </div>
                            ))}
                            {tooltip.count > 3 && (
                                <div className="text-slate-400 italic">
                                    +{tooltip.count - 3} altre...
                                </div>
                            )}
                        </div>
                    )}
                    <div className="text-slate-400 text-[10px] mt-2 text-center">
                        Clicca per vedere i dettagli
                    </div>
                </div>
            )}

            {/* Pannello dettagli data selezionata */}
            {selectedDate && (
                <div className="mt-4 border-t border-slate-200 pt-4">
                    <div className="flex items-center justify-between mb-3">
                        <h4 className="font-semibold text-slate-800 flex items-center gap-2">
                            <svg className="w-4 h-4 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                                      d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                            </svg>
                            {formatTooltipDate(selectedDate)}
                        </h4>
                        <button
                            onClick={() => setSelectedDate(null)}
                            className="text-slate-400 hover:text-slate-600 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="M6 18L18 6M6 6l12 12" />
                            </svg>
                        </button>
                    </div>
                    {selectedActivities.length === 0 ? (
                        <p className="text-sm text-slate-500 text-center py-4">Nessuna attività in questo giorno</p>
                    ) : (
                        <div className="space-y-2 max-h-64 overflow-y-auto">
                            {selectedActivities.map((activity, i) => (
                                <div
                                    key={i}
                                    className={`p-3 rounded-lg border border-slate-100 hover:bg-slate-50 transition-colors
                                               ${activity.projectId && onViewProject ? 'cursor-pointer' : ''}`}
                                    onClick={() => {
                                        if (activity.projectId && onViewProject) {
                                            onViewProject(activity.projectId);
                                        }
                                    }}
                                >
                                    <div className="flex items-start gap-3">
                                        <div className="flex-shrink-0 mt-0.5">
                                            {activity.type === 'notification' ? (
                                                <svg className="w-4 h-4 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                                                          d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
                                                </svg>
                                            ) : activity.type === 'project_create' ? (
                                                <svg className="w-4 h-4 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                                                          d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                                                </svg>
                                            ) : (
                                                <svg className="w-4 h-4 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                                                          d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                                                </svg>
                                            )}
                                        </div>
                                        <div className="flex-1 min-w-0">
                                            <p className="text-sm font-medium text-slate-800">{activity.title}</p>
                                            <p className="text-xs text-slate-500 truncate">{activity.message}</p>
                                            {activity.projectName && (
                                                <span className="inline-flex items-center mt-1 px-2 py-0.5 rounded text-xs bg-slate-100 text-slate-600">
                                                    {activity.projectName}
                                                </span>
                                            )}
                                        </div>
                                        <div className="text-xs text-slate-400 shrink-0">
                                            {new Date(activity.time).toLocaleTimeString('it-IT', { hour: '2-digit', minute: '2-digit' })}
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            )}
        </Card>
    );
}

window.ActivityHeatmapWidget = ActivityHeatmapWidget;
