// WelcomeView - Activity summary and project progress
function WelcomeView({ onViewChange, onViewProject }) {
    const { user } = useAuth();
    const { notifications, unreadCount, markAsRead, markAllAsRead, loading } = useNotifications();

    // Fetch all projects (not limited) for widgets
    const [allProjects, setAllProjects] = React.useState([]);
    const [projectsLoading, setProjectsLoading] = React.useState(true);

    // Check if user is admin
    const isAdmin = user?.role === 'admin';

    // Google Calendar state
    const [calendarAvailable, setCalendarAvailable] = React.useState(false);
    const [googleEvents, setGoogleEvents] = React.useState([]);

    // Function to load projects (includes archived for admin statistics)
    const loadProjects = React.useCallback(async () => {
        setProjectsLoading(true);
        try {
            const activeProjects = await ApiUtils.fetchProjects();
            // For admin, also fetch archived projects for team statistics
            if (isAdmin) {
                try {
                    const archivedProjects = await window.ApiProjects.fetchArchivedProjects();
                    setAllProjects([...activeProjects, ...archivedProjects]);
                } catch (err) {
                    // If archived fetch fails, just use active projects
                    console.error('Failed to fetch archived projects:', err);
                    setAllProjects(activeProjects);
                }
            } else {
                setAllProjects(activeProjects);
            }
        } catch (err) {
            console.error('Failed to fetch projects:', err);
        } finally {
            setProjectsLoading(false);
        }
    }, [isAdmin]);

    // Initial load - check if we need to refresh due to changes made in other views
    React.useEffect(() => {
        const needsRefresh = localStorage.getItem('rosa_projects_need_refresh');
        if (needsRefresh) {
            localStorage.removeItem('rosa_projects_need_refresh');
        }
        loadProjects();
    }, [loadProjects]);

    // Listen for project-related notifications and reload projects
    React.useEffect(() => {
        // Check if there's a new project-related notification
        const latestProjectNotification = notifications.find(n =>
            (n.type === 'step_status_changed' ||
             n.type === 'project_status_changed' ||
             n.type === 'project_assigned' ||
             n.type === 'project_unassigned') &&
            !n.is_read
        );

        if (latestProjectNotification) {
            // Reload projects when something project-related changes
            loadProjects();
        }
    }, [notifications, loadProjects]);

    // Listen for custom project update events (triggered by ProjectTimeline component)
    React.useEffect(() => {
        const handleProjectStepUpdate = () => {
            loadProjects();
        };

        window.addEventListener('project-step-updated', handleProjectStepUpdate);
        return () => {
            window.removeEventListener('project-step-updated', handleProjectStepUpdate);
        };
    }, [loadProjects]);

    // Also reload projects when the component becomes visible (user returns to this view)
    React.useEffect(() => {
        const handleVisibilityChange = () => {
            if (!document.hidden) {
                // Reload projects when tab becomes visible
                loadProjects();
            }
        };

        document.addEventListener('visibilitychange', handleVisibilityChange);
        return () => document.removeEventListener('visibilitychange', handleVisibilityChange);
    }, [loadProjects]);

    // Fetch Google Calendar events for a specific month
    const fetchGoogleEvents = React.useCallback((month, year) => {
        // Admin uses their own calendar endpoint, non-admin uses shared endpoint
        const fetchFn = isAdmin
            ? ApiUtils.getCalendarEvents
            : ApiUtils.getSharedCalendarEvents;

        fetchFn(month, year)
            .then(data => {
                setGoogleEvents(data.events || []);
            })
            .catch(error => {
                console.error('Error fetching Google Calendar events:', error);
                setGoogleEvents([]);
            });
    }, [isAdmin]);

    // Check calendar status and fetch events for current month
    React.useEffect(() => {
        if (isAdmin) {
            // Admin checks their own calendar status
            ApiUtils.getCalendarStatus()
                .then(status => {
                    setCalendarAvailable(status.connected);
                    if (status.connected) {
                        const now = new Date();
                        fetchGoogleEvents(now.getMonth() + 1, now.getFullYear());
                    }
                })
                .catch(console.error);
        } else {
            // Non-admin checks if shared calendar is available
            ApiUtils.getSharedCalendarStatus()
                .then(status => {
                    setCalendarAvailable(status.available);
                    if (status.available) {
                        const now = new Date();
                        fetchGoogleEvents(now.getMonth() + 1, now.getFullYear());
                    }
                })
                .catch(console.error);
        }
    }, [isAdmin, fetchGoogleEvents]);

    // Handle month change from calendar widget
    const handleCalendarMonthChange = React.useCallback((month, year) => {
        if (calendarAvailable) {
            fetchGoogleEvents(month, year);
        }
    }, [calendarAvailable, fetchGoogleEvents]);

    // Calculate project progress
    const getProjectProgress = React.useCallback((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) };
    }, []);

    // Filter non-archived projects for display widgets (Gantt, Calendar, etc.)
    const nonArchivedProjects = React.useMemo(() => {
        return allProjects.filter(p => !p.is_archived);
    }, [allProjects]);

    // Filter active projects for the progress widget (limited to 5)
    const activeProjects = React.useMemo(() => {
        return nonArchivedProjects
            .filter(p => p.status !== 'completato')
            .sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))
            .slice(0, 5);
    }, [nonArchivedProjects]);

    // Get current step (first non-completed step)
    const getCurrentStep = (project) => {
        if (!project.steps || project.steps.length === 0) return null;
        const sortedSteps = [...project.steps].sort((a, b) => a.step_order - b.step_order);
        return sortedSteps.find(s => s.status !== 'completato') || sortedSteps[sortedSteps.length - 1];
    };

    // Time-of-day greeting
    const getGreeting = () => {
        const hour = new Date().getHours();
        if (hour < 12) return 'Buongiorno';
        if (hour < 18) return 'Buon pomeriggio';
        return 'Buonasera';
    };

    // Calculate workload and deadline KPIs
    const workloadStats = React.useMemo(() => {
        const now = new Date();
        now.setHours(0, 0, 0, 0);

        // Overdue projects (past due_date, not completed/cancelled)
        const overdue = nonArchivedProjects.filter(p => {
            if (!p.due_date || p.status === 'completato' || p.is_cancelled) return false;
            const due = new Date(p.due_date);
            due.setHours(23, 59, 59, 999);
            return due < now;
        }).length;

        // Due soon (within 7 days, not overdue)
        const dueSoon = nonArchivedProjects.filter(p => {
            if (!p.due_date || p.status === 'completato' || p.is_cancelled) return false;
            const due = new Date(p.due_date);
            due.setHours(0, 0, 0, 0);
            const daysUntil = Math.ceil((due - now) / (1000 * 60 * 60 * 24));
            return daysUntil >= 0 && daysUntil <= 7;
        }).length;

        // My active projects (assigned to me, not completed/cancelled)
        const myActive = nonArchivedProjects.filter(p => {
            if (p.status === 'completato' || p.is_cancelled) return false;
            const isAssignedToMe = p.assignments?.some(a => a.user_id === user?.id) || p.my_assignment;
            return isAssignedToMe;
        }).length;

        // Completion rate (using all projects including archived)
        const myAllProjects = allProjects.filter(p => {
            const isAssignedToMe = p.assignments?.some(a => a.user_id === user?.id) || p.my_assignment;
            return isAssignedToMe;
        });
        const myCompleted = myAllProjects.filter(p =>
            p.status === 'completato' || (p.is_archived && !p.is_cancelled)
        ).length;
        const completionRate = myAllProjects.length > 0
            ? Math.round((myCompleted / myAllProjects.length) * 100)
            : 0;

        return { overdue, dueSoon, myActive, completionRate, myTotal: myAllProjects.length };
    }, [nonArchivedProjects, allProjects, user]);

    // Get notification icon by type
    const getNotificationIcon = (type) => {
        const iconMap = {
            project_assigned: (
                <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="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z" />
                </svg>
            ),
            project_unassigned: (
                <svg className="w-5 h-5 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7a4 4 0 11-8 0 4 4 0 018 0zM9 14a6 6 0 00-6 6v1h12v-1a6 6 0 00-6-6zM21 12h-6" />
                </svg>
            ),
            project_status_changed: (
                <svg className="w-5 h-5 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
            ),
            step_status_changed: (
                <svg className="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
                </svg>
            ),
            comment_added: (
                <svg className="w-5 h-5 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                </svg>
            ),
        };
        return iconMap[type] || (
            <svg className="w-5 h-5 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
        );
    };

    // Dynamic color for completion rate
    const getCompletionRateColors = (rate) => {
        if (rate >= 75) return { color: 'text-green-600', bg: 'bg-green-50', iconColor: 'text-green-500' };
        if (rate >= 50) return { color: 'text-amber-600', bg: 'bg-amber-50', iconColor: 'text-amber-500' };
        return { color: 'text-slate-600', bg: 'bg-slate-50', iconColor: 'text-slate-500' };
    };
    const completionColors = getCompletionRateColors(workloadStats.completionRate);

    const statCards = [
        {
            label: 'Scadute',
            value: workloadStats.overdue,
            icon: (
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                          d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
            ),
            color: 'text-red-600',
            bg: 'bg-red-50',
            iconColor: 'text-red-500'
        },
        {
            label: 'In Scadenza',
            sublabel: 'prossimi 7 giorni',
            value: workloadStats.dueSoon,
            icon: (
                <svg className="w-6 h-6" 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>
            ),
            color: 'text-amber-600',
            bg: 'bg-amber-50',
            iconColor: 'text-amber-500'
        },
        {
            label: 'Le Mie Pratiche',
            sublabel: 'attive',
            value: workloadStats.myActive,
            icon: (
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                          d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
                </svg>
            ),
            color: 'text-blue-600',
            bg: 'bg-blue-50',
            iconColor: 'text-blue-500'
        },
        {
            label: 'Completate',
            sublabel: workloadStats.myTotal > 0 ? `${workloadStats.myTotal} totali` : null,
            value: `${workloadStats.completionRate}%`,
            icon: (
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                          d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
            ),
            color: completionColors.color,
            bg: completionColors.bg,
            iconColor: completionColors.iconColor
        },
    ];

    return (
        <div className="p-8 space-y-6">
            {/* Greeting Header */}
            <div className="mb-2">
                <h1 className="text-2xl font-bold text-slate-800">
                    {getGreeting()}, {user?.full_name?.split(' ')[0] || 'Utente'}
                </h1>
                <p className="text-slate-500 mt-1">Ecco un riepilogo della tua attività</p>
            </div>

            {/* Workload & Deadline KPIs */}
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                {statCards.map(stat => (
                    <Card key={stat.label} className={`p-5 ${stat.bg}`}>
                        <div className="flex items-center gap-3">
                            <div className={stat.iconColor}>
                                {stat.icon}
                            </div>
                            <div>
                                <div className={`text-2xl font-bold ${stat.color}`}>{stat.value}</div>
                                <div className="text-sm text-slate-600 font-medium">{stat.label}</div>
                                {stat.sublabel && (
                                    <div className="text-xs text-slate-400">{stat.sublabel}</div>
                                )}
                            </div>
                        </div>
                    </Card>
                ))}
            </div>

            {/* Due Date Alerts (full width) - only non-archived projects */}
            {!projectsLoading && (
                <DueDateAlertsWidget projects={nonArchivedProjects} onViewChange={onViewChange} />
            )}

            {/* Main Content Grid - 2/3 + 1/3 layout */}
            <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
                {/* Left Column - 2/3 width */}
                <div className="xl:col-span-2 space-y-6">
                    {/* Gantt Chart - only non-archived projects */}
                    {!projectsLoading && (
                        <ProjectGanttChart projects={nonArchivedProjects} onProjectClick={onViewProject} />
                    )}

                    {/* Calendar Widget - only non-archived projects */}
                    {projectsLoading ? (
                        <Card className="p-6">
                            <div className="py-8 text-center"><Spinner size="md" /></div>
                        </Card>
                    ) : (
                        <DeadlinesCalendarWidget
                            projects={nonArchivedProjects}
                            onViewChange={onViewChange}
                            googleEvents={calendarAvailable ? googleEvents : []}
                            onMonthChange={calendarAvailable ? handleCalendarMonthChange : undefined}
                        />
                    )}

                    {/* Activity Heatmap - only non-archived projects */}
                    <ActivityHeatmapWidget notifications={notifications} projects={nonArchivedProjects} onViewProject={onViewProject} />
                </div>

                {/* Right Column - 1/3 width */}
                <div className="space-y-6">
                    {/* Team Statistics - Admin only (includes archived for complete stats) */}
                    {isAdmin && (
                        projectsLoading ? (
                            <Card className="p-6">
                                <div className="py-8 text-center"><Spinner size="md" /></div>
                            </Card>
                        ) : (
                            <TeamOverviewWidget projects={allProjects} isAdmin={isAdmin} />
                        )
                    )}

                    {/* Recent Activity */}
                    <Card className="p-6">
                        <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-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                                          d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                                </svg>
                                Attivita Recente
                            </h3>
                            {unreadCount > 0 && (
                                <button
                                    onClick={markAllAsRead}
                                    className="text-sm text-brand-600 hover:text-brand-700 font-medium"
                                >
                                    Segna tutte come lette
                                </button>
                            )}
                        </div>
                        {loading ? (
                            <div className="py-8 text-center"><Spinner size="md" /></div>
                        ) : notifications.length === 0 ? (
                            <p className="text-sm text-slate-500 text-center py-8">Nessuna attivita recente</p>
                        ) : (
                            <div className="space-y-2">
                                {notifications.slice(0, 6).map(notification => (
                                    <div
                                        key={notification.id}
                                        className={`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors
                                            ${!notification.is_read ? 'bg-blue-50/50 border-blue-100' : 'border-slate-100 hover:bg-slate-50'}`}
                                        onClick={() => {
                                            if (!notification.is_read) markAsRead(notification.id);
                                            if (notification.data?.project_id && onViewProject) {
                                                onViewProject(notification.data.project_id);
                                            }
                                        }}
                                    >
                                        <div className="flex-shrink-0">{getNotificationIcon(notification.type)}</div>
                                        <div className="flex-1 min-w-0">
                                            <p className={`text-sm ${!notification.is_read ? 'font-semibold text-slate-900' : 'text-slate-700'}`}>
                                                {notification.title}
                                            </p>
                                            <p className="text-xs text-slate-500 truncate">{notification.message}</p>
                                        </div>
                                        <div className="flex items-center gap-2 shrink-0">
                                            <span className="text-xs text-slate-400">
                                                {Formatters.formatRelativeTime(notification.created_at)}
                                            </span>
                                            {!notification.is_read && (
                                                <span className="w-2 h-2 rounded-full bg-blue-500"></span>
                                            )}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                    </Card>

                    {/* Project Progress */}
                    <Card className="p-6">
                        <h3 className="font-semibold text-slate-900 mb-4 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="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
                            </svg>
                            Pratiche in Corso
                        </h3>
                        {projectsLoading ? (
                            <div className="py-8 text-center"><Spinner size="md" /></div>
                        ) : activeProjects.length === 0 ? (
                            <p className="text-sm text-slate-500 text-center py-8">Nessuna pratica attiva</p>
                        ) : (
                            <div className="space-y-3">
                                {activeProjects.map(project => {
                                    const progress = getProjectProgress(project);
                                    const currentStep = getCurrentStep(project);
                                    return (
                                        <div
                                            key={project.id}
                                            className="p-3 rounded-lg border border-slate-100 hover:bg-slate-50 cursor-pointer transition-colors"
                                            onClick={() => onViewChange('projects')}
                                        >
                                            <div className="flex items-center justify-between mb-2">
                                                <span className="font-medium text-slate-800 truncate flex-1 mr-2">
                                                    {project.name}
                                                </span>
                                                <span className="text-xs text-slate-400 shrink-0">
                                                    {Formatters.formatRelativeTime(project.updated_at)}
                                                </span>
                                            </div>
                                            <div className="flex items-center gap-3">
                                                <div className="flex-1 h-2 bg-slate-100 rounded-full overflow-hidden">
                                                    <div
                                                        className="h-full bg-brand-500 rounded-full transition-all"
                                                        style={{ width: `${progress.percent}%` }}
                                                    />
                                                </div>
                                                <span className="text-xs text-slate-500 w-10 text-right">
                                                    {progress.percent}%
                                                </span>
                                            </div>
                                            {currentStep && (
                                                <div className="mt-2 flex items-center gap-2">
                                                    <Badge variant="info" size="sm">{currentStep.step_name}</Badge>
                                                    <span className="text-xs text-slate-400">
                                                        {progress.completed}/{progress.total} completati
                                                    </span>
                                                </div>
                                            )}
                                            {/* Assigned Users */}
                                            {project.assignments && project.assignments.length > 0 && (
                                                <div className="mt-2 flex items-center gap-2">
                                                    <div className="flex -space-x-2">
                                                        {project.assignments.slice(0, 3).map((assignment) => {
                                                            const avatarUrl = assignment.user_avatar ? window.ApiUsers?.getAvatarUrl(assignment.user_avatar) : null;
                                                            return avatarUrl ? (
                                                                <img
                                                                    key={assignment.id}
                                                                    src={avatarUrl}
                                                                    alt={assignment.user_name || assignment.user_email}
                                                                    className="w-6 h-6 rounded-full border-2 border-white object-cover"
                                                                    title={assignment.user_name || assignment.user_email}
                                                                />
                                                            ) : (
                                                                <div
                                                                    key={assignment.id}
                                                                    className="w-6 h-6 rounded-full bg-brand-100 border-2 border-white flex items-center justify-center"
                                                                    title={assignment.user_name || assignment.user_email}
                                                                >
                                                                    <span className="text-xs font-semibold text-brand-600">
                                                                        {(assignment.user_name || assignment.user_email || '?').charAt(0).toUpperCase()}
                                                                    </span>
                                                                </div>
                                                            );
                                                        })}
                                                        {project.assignments.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">
                                                                    +{project.assignments.length - 3}
                                                                </span>
                                                            </div>
                                                        )}
                                                    </div>
                                                    <span className="text-xs text-slate-400">
                                                        {project.assignments.length === 1 ? '1 assegnato' : `${project.assignments.length} assegnati`}
                                                    </span>
                                                </div>
                                            )}
                                        </div>
                                    );
                                })}
                            </div>
                        )}
                        <Button variant="ghost" size="sm" className="w-full mt-4" onClick={() => onViewChange('projects')}>
                            Vedi tutte le pratiche
                        </Button>
                    </Card>
                </div>
            </div>
        </div>
    );
}

window.WelcomeView = WelcomeView;
