// ProjectGanttChart - Gantt chart visualization for active projects

function ProjectGanttChart({ projects, onProjectClick }) {
    const [viewMode, setViewMode] = React.useState('month'); // 'week', 'month', 'quarter'
    const [collapsed, setCollapsed] = React.useState(false);
    const containerRef = React.useRef(null);
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    // Filter projects that have at least a start_date
    const projectsWithDates = projects.filter(p => p.start_date);

    if (projectsWithDates.length === 0) {
        return null;
    }

    // Calculate date range based on all projects
    const calculateDateRange = () => {
        let minDate = new Date();
        let maxDate = new Date();

        projectsWithDates.forEach(project => {
            const startDate = new Date(project.start_date);
            const endDate = project.due_date ? new Date(project.due_date) : new Date(startDate.getTime() + 30 * 24 * 60 * 60 * 1000);

            if (startDate < minDate) minDate = startDate;
            if (endDate > maxDate) maxDate = endDate;
        });

        // Add padding
        minDate.setDate(minDate.getDate() - 7);
        maxDate.setDate(maxDate.getDate() + 14);

        return { minDate, maxDate };
    };

    const { minDate, maxDate } = calculateDateRange();

    // Generate time periods based on view mode
    const generatePeriods = () => {
        const periods = [];
        let current = new Date(minDate);

        if (viewMode === 'week') {
            current.setDate(current.getDate() - current.getDay() + 1);
            while (current <= maxDate) {
                const weekStart = new Date(current);
                const weekEnd = new Date(current);
                weekEnd.setDate(weekEnd.getDate() + 6);
                periods.push({
                    start: weekStart,
                    end: weekEnd,
                    label: `${weekStart.getDate()} ${weekStart.toLocaleDateString('it-IT', { month: 'short' })}`
                });
                current.setDate(current.getDate() + 7);
            }
        } else if (viewMode === 'month') {
            current.setDate(1);
            while (current <= maxDate) {
                const monthStart = new Date(current);
                const monthEnd = new Date(current.getFullYear(), current.getMonth() + 1, 0);
                periods.push({
                    start: monthStart,
                    end: monthEnd,
                    label: current.toLocaleDateString('it-IT', { month: 'short', year: '2-digit' })
                });
                current.setMonth(current.getMonth() + 1);
            }
        } else {
            current.setDate(1);
            current.setMonth(Math.floor(current.getMonth() / 3) * 3);
            while (current <= maxDate) {
                const quarterStart = new Date(current);
                const quarterEnd = new Date(current.getFullYear(), current.getMonth() + 3, 0);
                const quarterNum = Math.floor(current.getMonth() / 3) + 1;
                periods.push({
                    start: quarterStart,
                    end: quarterEnd,
                    label: `Q${quarterNum} ${current.getFullYear()}`
                });
                current.setMonth(current.getMonth() + 3);
            }
        }

        return periods;
    };

    const periods = generatePeriods();
    const totalDays = Math.ceil((maxDate - minDate) / (1000 * 60 * 60 * 24));

    const getProjectBar = (project) => {
        const startDate = new Date(project.start_date);
        const endDate = project.due_date ? new Date(project.due_date) : new Date(startDate.getTime() + 14 * 24 * 60 * 60 * 1000);

        const startOffset = Math.max(0, Math.ceil((startDate - minDate) / (1000 * 60 * 60 * 24)));
        const duration = Math.max(1, Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24)));

        const leftPercent = (startOffset / totalDays) * 100;
        const widthPercent = (duration / totalDays) * 100;

        const isOverdue = project.due_date && new Date(project.due_date) < today && project.status !== 'completed';
        const daysUntilDue = project.due_date ? Math.ceil((new Date(project.due_date) - today) / (1000 * 60 * 60 * 24)) : null;
        const isNearingDeadline = daysUntilDue !== null && daysUntilDue > 0 && daysUntilDue <= 7;

        return { leftPercent, widthPercent, isOverdue, isNearingDeadline, daysUntilDue };
    };

    const getBarColor = (project, isOverdue, isNearingDeadline) => {
        if (project.status === 'completed') return 'bg-green-500';
        if (isOverdue) return 'bg-red-500';
        if (isNearingDeadline) return 'bg-amber-500';
        // Normal projects use priority-based colors (distinct from warning colors)
        switch (project.priority) {
            case 'high': return 'bg-purple-500';
            case 'medium': return 'bg-blue-500';
            default: return 'bg-slate-400';
        }
    };

    const todayOffset = Math.ceil((today - minDate) / (1000 * 60 * 60 * 24));
    const todayPercent = (todayOffset / totalDays) * 100;

    const sortedProjects = [...projectsWithDates].sort((a, b) =>
        new Date(a.start_date) - new Date(b.start_date)
    );

    return (
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
            <div
                className="px-5 py-3 border-b border-slate-100 flex items-center justify-between cursor-pointer hover:bg-slate-50 transition-colors"
                onClick={() => setCollapsed(!collapsed)}
            >
                <div className="flex items-center gap-3">
                    <svg
                        className={`w-5 h-5 text-slate-400 transition-transform ${collapsed ? '' : 'rotate-90'}`}
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                    >
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                    </svg>
                    <div className="flex items-center gap-2">
                        <svg className="w-5 h-5 text-brand-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>
                        <h3 className="font-semibold text-slate-800">Timeline Pratiche</h3>
                    </div>
                    <span className="px-2 py-0.5 text-xs font-medium rounded-full bg-slate-100 text-slate-600">
                        {projectsWithDates.length} progetti
                    </span>
                </div>

                {!collapsed && (
                    <div className="flex items-center gap-2" onClick={e => e.stopPropagation()}>
                        <div className="hidden md:flex items-center gap-4 mr-4 text-xs text-slate-500">
                            <span className="flex items-center gap-1">
                                <span className="w-3 h-3 rounded bg-purple-500"></span> Alta
                            </span>
                            <span className="flex items-center gap-1">
                                <span className="w-3 h-3 rounded bg-blue-500"></span> Media
                            </span>
                            <span className="flex items-center gap-1">
                                <span className="w-3 h-3 rounded bg-slate-400"></span> Bassa
                            </span>
                        </div>
                        <div className="flex items-center rounded-lg border border-slate-200 overflow-hidden">
                            {['week', 'month', 'quarter'].map(mode => (
                                <button
                                    key={mode}
                                    onClick={() => setViewMode(mode)}
                                    className={`px-3 py-1.5 text-xs font-medium transition-colors ${
                                        viewMode === mode
                                            ? 'bg-brand-500 text-white'
                                            : 'bg-white text-slate-600 hover:bg-slate-50'
                                    }`}
                                >
                                    {mode === 'week' ? 'Sett.' : mode === 'month' ? 'Mese' : 'Trim.'}
                                </button>
                            ))}
                        </div>
                    </div>
                )}
            </div>

            {!collapsed && (
                <div className="overflow-x-auto" ref={containerRef}>
                    <div className="min-w-[800px]">
                        {/* Sticky header row */}
                        <div className="flex border-b border-slate-100 sticky top-0 z-20 bg-white">
                            <div className="w-48 flex-shrink-0 px-4 py-2 bg-slate-50 border-r border-slate-100">
                                <span className="text-xs font-medium text-slate-500 uppercase tracking-wide">Pratica</span>
                            </div>
                            <div className="w-32 flex-shrink-0 px-4 py-2 bg-slate-50 border-r border-slate-100">
                                <span className="text-xs font-medium text-slate-500 uppercase tracking-wide">Assegnati</span>
                            </div>
                            <div className="flex-1 flex">
                                {periods.map((period, idx) => (
                                    <div
                                        key={idx}
                                        className="flex-1 px-2 py-2 text-center border-r border-slate-100 last:border-r-0 bg-slate-50"
                                    >
                                        <span className="text-xs font-medium text-slate-600">{period.label}</span>
                                    </div>
                                ))}
                            </div>
                        </div>

                        {/* Scrollable project rows container - max height of ~10 rows (400px) */}
                        <div className="max-h-[400px] overflow-y-auto">
                            <div className="relative">
                                {/* Today marker - spans full height of content */}
                                {todayPercent >= 0 && todayPercent <= 100 && (
                                    <div
                                        className="absolute top-0 bottom-0 w-0.5 bg-red-400 z-10 pointer-events-none"
                                        style={{ left: `calc(320px + (100% - 320px) * ${todayPercent / 100})` }}
                                    >
                                        <div className="sticky top-0 left-1/2 -translate-x-1/2 px-1.5 py-0.5 bg-red-400 text-white text-[10px] font-medium rounded whitespace-nowrap">
                                            Oggi
                                        </div>
                                    </div>
                                )}

                                {sortedProjects.map((project, idx) => {
                                const { leftPercent, widthPercent, isOverdue, isNearingDeadline, daysUntilDue } = getProjectBar(project);
                                const barColor = getBarColor(project, isOverdue, isNearingDeadline);
                                const assignees = project.assignments || [];

                                return (
                                    <div
                                        key={project.id}
                                        className={`flex items-center border-b border-slate-100 hover:bg-slate-50 transition-colors ${
                                            idx % 2 === 0 ? 'bg-white' : 'bg-slate-50/30'
                                        }`}
                                    >
                                        <div
                                            className="w-48 flex-shrink-0 px-4 py-3 border-r border-slate-100 cursor-pointer"
                                            onClick={() => onProjectClick && onProjectClick(project.id)}
                                        >
                                            <div className="flex items-center gap-2">
                                                <span
                                                    className={`w-2 h-2 rounded-full flex-shrink-0 ${
                                                        project.priority === 'high'
                                                            ? 'bg-purple-500'
                                                            : project.priority === 'medium'
                                                                ? 'bg-blue-500'
                                                                : 'bg-slate-400'
                                                    }`}
                                                />
                                                <span className="text-sm font-medium text-slate-700 truncate" title={project.name}>
                                                    {project.name}
                                                </span>
                                            </div>
                                        </div>

                                        {/* Assignees Column */}
                                        <div className="w-32 flex-shrink-0 px-2 py-2 border-r border-slate-100">
                                            {assignees.length > 0 ? (
                                                <div className="flex items-center -space-x-1">
                                                    {assignees.slice(0, 3).map((assignment, i) => {
                                                        const name = assignment.user_name || assignment.user_email || '?';
                                                        const initials = name.split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase();
                                                        return (
                                                            <div
                                                                key={assignment.user_id || i}
                                                                className="w-6 h-6 rounded-full bg-blue-100 border-2 border-white flex items-center justify-center"
                                                                title={name}
                                                            >
                                                                <span className="text-[10px] font-medium text-blue-700">{initials}</span>
                                                            </div>
                                                        );
                                                    })}
                                                    {assignees.length > 3 && (
                                                        <div
                                                            className="w-6 h-6 rounded-full bg-slate-200 border-2 border-white flex items-center justify-center"
                                                            title={assignees.slice(3).map(a => a.user_name || a.user_email).join(', ')}
                                                        >
                                                            <span className="text-[10px] font-medium text-slate-600">+{assignees.length - 3}</span>
                                                        </div>
                                                    )}
                                                </div>
                                            ) : (
                                                <span className="text-xs text-slate-400">-</span>
                                            )}
                                        </div>

                                        <div className="flex-1 relative h-10 px-2">
                                            <div className="absolute inset-0 flex">
                                                {periods.map((_, idx) => (
                                                    <div key={idx} className="flex-1 border-r border-slate-100 last:border-r-0" />
                                                ))}
                                            </div>

                                            <div
                                                className={`absolute top-1/2 -translate-y-1/2 h-6 rounded cursor-pointer transition-all hover:scale-y-110 hover:shadow-md ${barColor}`}
                                                style={{
                                                    left: `${leftPercent}%`,
                                                    width: `${Math.max(widthPercent, 2)}%`,
                                                    minWidth: '20px'
                                                }}
                                                onClick={() => onProjectClick && onProjectClick(project.id)}
                                                title={`${project.name}\nInizio: ${new Date(project.start_date).toLocaleDateString('it-IT')}\n${project.due_date ? 'Scadenza: ' + new Date(project.due_date).toLocaleDateString('it-IT') : 'Scadenza non impostata'}`}
                                            >
                                                {widthPercent > 8 && (
                                                    <span className="absolute inset-0 flex items-center justify-center text-xs font-medium text-white truncate px-2">
                                                        {project.name.length > 15 ? project.name.substring(0, 15) + '...' : project.name}
                                                    </span>
                                                )}

                                                {(isOverdue || isNearingDeadline) && (
                                                    <span className="absolute -right-1 -top-1 flex h-4 w-4">
                                                        {isOverdue ? (
                                                            <span className="relative inline-flex rounded-full h-4 w-4 bg-red-600 items-center justify-center">
                                                                <span className="text-white text-[10px] font-bold">!</span>
                                                            </span>
                                                        ) : (
                                                            <span className="relative inline-flex rounded-full h-4 w-4 bg-amber-600 items-center justify-center text-white text-[9px] font-medium">
                                                                {daysUntilDue}
                                                            </span>
                                                        )}
                                                    </span>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                );
                            })}
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

window.ProjectGanttChart = ProjectGanttChart;
