// MyProjectsView - Vista progetti assegnati per utenti

function MyProjectsView({ pendingProjectId, onPendingHandled, onViewProject }) {
    const { user: currentUser, isAdmin } = useAuth();
    const toast = useToast();
    const [projects, setProjects] = React.useState([]);
    const [timelines, setTimelines] = React.useState({});
    const [loading, setLoading] = React.useState(true);
    const [editingProject, setEditingProject] = React.useState(null);
    const [timelineProject, setTimelineProject] = React.useState(null);
    const [confirmModal, setConfirmModal] = React.useState(null);

    const loadData = async () => {
        setLoading(true);
        try {
            const projectsData = await ApiUtils.fetchProjects();
            // Sort by creation time (newest first) and force new array reference for React to detect changes
            const sortedProjects = [...projectsData].sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
            setProjects(sortedProjects);
            
            // Fetch timeline data for each project to get step progress
            const timelinePromises = projectsData.map(async (project) => {
                try {
                    const timeline = await ApiUtils.getProjectTimeline(project.id, false);
                    return { projectId: project.id, timeline };
                } catch (err) {
                    console.error(`Failed to load timeline for project ${project.id}:`, err);
                    return { projectId: project.id, timeline: null };
                }
            });
            
            const timelineResults = await Promise.all(timelinePromises);
            const timelinesMap = {};
            timelineResults.forEach(({ projectId, timeline }) => {
                timelinesMap[projectId] = timeline;
            });
            setTimelines(timelinesMap);
        } catch (err) {
            toast('Errore nel caricamento progetti: ' + err.message, 'error');
        } finally {
            setLoading(false);
        }
    };

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

    // Handle pending project from notification click
    React.useEffect(() => {
        if (pendingProjectId && projects.length > 0 && !loading) {
            const project = projects.find(p => p.id === pendingProjectId);
            if (project) {
                setTimelineProject(project);
            }
            // Clear the pending project
            if (onPendingHandled) {
                onPendingHandled();
            }
        }
    }, [pendingProjectId, projects, loading, onPendingHandled]);

    const getProgressInfo = (projectId) => {
        const timeline = timelines[projectId];
        if (!timeline || !timeline.steps || timeline.steps.length === 0) {
            return { completed: 0, total: 0, percent: 0, lastUpdated: null };
        }
        
        const completed = timeline.steps.filter(s => s.status === 'completato').length;
        const total = timeline.steps.length;
        const percent = Math.round((completed / total) * 100);
        
        // Find the most recent update across all steps
        let lastUpdated = null;
        timeline.steps.forEach(step => {
            const stepDate = step.updated_at ? new Date(step.updated_at) : null;
            if (stepDate && (!lastUpdated || stepDate > lastUpdated)) {
                lastUpdated = stepDate;
            }
        });
        
        return { completed, total, percent, lastUpdated };
    };

    // Use shared utilities
    const formatRelativeTime = Formatters.formatRelativeTime;

    // Refresh timeline data for a specific project after step changes
    const refreshProjectTimeline = async (projectId) => {
        try {
            const timeline = await ApiUtils.getProjectTimeline(projectId, false);
            setTimelines(prev => ({
                ...prev,
                [projectId]: timeline
            }));
        } catch (err) {
            console.error(`Failed to refresh timeline for project ${projectId}:`, err);
        }
    };

    const handleCancel = (project) => {
        setConfirmModal({
            type: 'cancel',
            project,
            title: 'Annulla Pratica',
            message: `Sei sicuro di voler annullare la pratica "${project.name}"?\n\nIl workflow sara bloccato e non sara possibile modificare gli stati degli step.`,
            confirmText: 'Annulla Pratica',
            variant: 'danger',
        });
    };

    const handleUncancel = (project) => {
        setConfirmModal({
            type: 'uncancel',
            project,
            title: 'Ripristina Pratica',
            message: `Sei sicuro di voler ripristinare la pratica "${project.name}"?\n\nIl workflow sara sbloccato.`,
            confirmText: 'Ripristina',
            variant: 'info',
        });
    };

    const executeConfirmedAction = async () => {
        if (!confirmModal) return;

        const { type, project } = confirmModal;
        setConfirmModal({ ...confirmModal, loading: true });

        try {
            if (type === 'cancel') {
                await ApiUtils.cancelProject(project.id);
                toast('Pratica annullata', 'success');
            } else if (type === 'uncancel') {
                await ApiUtils.uncancelProject(project.id);
                toast('Pratica ripristinata', 'success');
            }
            setConfirmModal(null);
            loadData();
        } catch (err) {
            toast('Errore: ' + err.message, 'error');
            setConfirmModal(null);
        }
    };

    // If admin, redirect to full projects view
    if (isAdmin) {
        return (
            <div className="p-8 text-center">
                <div className="text-slate-400 text-lg">
                    Come admin, usa la sezione "Pratiche" nel menu Gestione per vedere tutte le pratiche.
                </div>
            </div>
        );
    }

    return (
        <div className="p-6 space-y-6">
            {/* Header */}
            <div>
                <h2 className="text-2xl font-bold text-slate-800">Le Mie Pratiche</h2>
                <p className="text-slate-500 mt-1">Pratiche a cui sei assegnato</p>
            </div>

            {/* Projects Grid */}
            {loading ? (
                <div className="p-12 text-center">
                    <Spinner size="lg" />
                    <p className="text-slate-500 mt-4">Caricamento progetti...</p>
                </div>
            ) : projects.length === 0 ? (
                <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-12 text-center">
                    <svg className="w-16 h-16 text-slate-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} 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>
                    <p className="text-slate-500">Non sei ancora assegnato a nessuna pratica</p>
                    <p className="text-slate-400 text-sm mt-2">Contatta un amministratore per essere assegnato a una pratica</p>
                </div>
            ) : (
                <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
                    {projects.map(project => {
                        const progressInfo = getProgressInfo(project.id);
                        
                        return (
                            <div
                                key={project.id}
                                className={`bg-white rounded-xl shadow-sm border overflow-hidden hover:shadow-md transition-shadow flex flex-col h-full relative ${
                                    project.is_cancelled
                                        ? 'border-red-200 opacity-75'
                                        : 'border-slate-200'
                                }`}
                            >
                                {/* Cancelled Banner */}
                                {project.is_cancelled && (
                                    <div className="absolute top-0 left-0 right-0 bg-red-500/90 text-white text-xs font-bold text-center py-1 uppercase tracking-wide z-10">
                                        Annullato
                                    </div>
                                )}

                                {/* Progress Header - Clickable */}
                                <div
                                    className={`px-5 pt-4 pb-3 border-b border-slate-100 cursor-pointer hover:bg-slate-50 transition-colors ${project.is_cancelled ? 'mt-6' : ''}`}
                                    onClick={() => onViewProject && onViewProject(project.id)}
                                >
                                    <div className="flex items-center justify-between mb-2">
                                        <div className="flex items-center gap-2">
                                            <span className="text-xs font-semibold text-slate-500 uppercase tracking-wide">Avanzamento</span>
                                            <span className={`px-2 py-0.5 text-xs font-bold rounded-full ${
                                                progressInfo.percent === 100 
                                                    ? 'bg-green-100 text-green-700' 
                                                    : progressInfo.percent >= 50 
                                                        ? 'bg-blue-100 text-blue-700'
                                                        : progressInfo.percent > 0
                                                            ? 'bg-amber-100 text-amber-700'
                                                            : 'bg-slate-100 text-slate-500'
                                            }`}>
                                                {progressInfo.completed}/{progressInfo.total}
                                            </span>
                                        </div>
                                        <span className="text-xs text-slate-400">
                                            {progressInfo.lastUpdated ? `Agg. ${formatRelativeTime(progressInfo.lastUpdated)}` : '\u00A0'}
                                        </span>
                                    </div>
                                    <div className="w-full h-2 bg-slate-100 rounded-full overflow-hidden">
                                        <div 
                                            className={`h-full transition-all duration-500 ${StatusBadge.getProgressColor(progressInfo.percent)}`}
                                            style={{ width: `${progressInfo.percent}%` }}
                                        />
                                    </div>
                                    <div className="mt-1 text-right">
                                        <span className="text-xs font-medium text-slate-500">{progressInfo.percent}%</span>
                                    </div>
                                </div>

                                {/* Main Content - Clickable */}
                                <div
                                    className="p-5 flex-1 flex flex-col cursor-pointer hover:bg-slate-50/50 transition-colors"
                                    onClick={() => onViewProject && onViewProject(project.id)}
                                >
                                    {/* Title & Priority */}
                                    <div className="flex items-start justify-between gap-3 mb-3">
                                        <h3 className="font-semibold text-slate-800 leading-tight">{project.name}</h3>
                                        <PriorityBadge priority={project.priority} />
                                    </div>

                                    {/* Meta Info - fixed height section */}
                                    <div className="space-y-1.5 text-sm mb-4">
                                        <div className="flex items-center gap-2 text-slate-600">
                                            <svg className="w-4 h-4 text-slate-400 flex-shrink-0" 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>
                                            <span>
                                                {project.start_date
                                                    ? new Date(project.start_date).toLocaleDateString('it-IT', { day: '2-digit', month: 'short', year: 'numeric' })
                                                    : 'Data non impostata'
                                                }
                                            </span>
                                        </div>

                                        {/* Scadenza */}
                                        <div className="flex items-center gap-2 text-slate-600">
                                            <svg className="w-4 h-4 text-slate-400 flex-shrink-0" 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>
                                            <span className="text-slate-500">Scadenza:</span>
                                            <span className={project.due_date ? '' : 'text-slate-400'}>
                                                {project.due_date
                                                    ? new Date(project.due_date).toLocaleDateString('it-IT', { day: '2-digit', month: 'short', year: 'numeric' })
                                                    : 'Non impostata'
                                                }
                                            </span>
                                        </div>

                                        {/* Creato da */}
                                        <div className="flex items-center gap-2 text-slate-600">
                                            <svg className="w-4 h-4 text-slate-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                                            </svg>
                                            <span className="text-slate-500">Creato da:</span>
                                            <span className="font-medium">{project.created_by_name || 'N/A'}</span>
                                        </div>

                                        {/* Assegnato a te da */}
                                        {project.my_assignment?.assigned_by_name && (
                                            <div className="flex items-center gap-2 text-slate-600">
                                                <svg className="w-4 h-4 text-slate-400 flex-shrink-0" 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>
                                                <span className="text-slate-500">Assegnato a te da:</span>
                                                <span className="font-medium">{project.my_assignment.assigned_by_name}</span>
                                            </div>
                                        )}

                                        {project.reference_id && (
                                            <div className="flex items-center gap-2 text-slate-600">
                                                <svg className="w-4 h-4 text-slate-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14" />
                                                </svg>
                                                <span className="font-mono text-xs">{project.reference_id}</span>
                                            </div>
                                        )}
                                    </div>

                                    {/* Description & Notes - flex-grow to push footer down */}
                                    <div className="flex-1 min-h-[60px]">
                                        {project.description && (
                                            <p className="text-sm text-slate-600 line-clamp-2 mb-2">{project.description}</p>
                                        )}
                                        {project.notes && (
                                            <div className="p-2.5 bg-slate-50 rounded-lg border border-slate-100">
                                                <p className="text-xs font-medium text-slate-500 mb-0.5">Note:</p>
                                                <p className="text-sm text-slate-600 line-clamp-2">{project.notes}</p>
                                            </div>
                                        )}
                                    </div>
                                </div>

                                {/* Footer - always at bottom */}
                                <div className="px-5 py-4 bg-slate-50 border-t border-slate-100 space-y-2 mt-auto">
                                    <button
                                        onClick={() => setTimelineProject(project)}
                                        className="w-full flex items-center justify-center gap-2 px-3 py-2.5 text-sm font-medium text-white bg-brand-500 hover:bg-brand-600 rounded-lg transition-colors"
                                    >
                                        <svg className="w-4 h-4" 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-3 7h3m-3 4h3m-6-4h.01M9 16h.01" />
                                        </svg>
                                        Gestisci Workflow
                                    </button>
                                    <div className="flex gap-2">
                                        <button
                                            onClick={() => setEditingProject(project)}
                                            className="flex-1 flex items-center justify-center gap-2 px-3 py-2 text-sm font-medium text-slate-600 hover:bg-white hover:border-slate-200 border border-transparent rounded-lg transition-colors"
                                        >
                                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                            </svg>
                                            Modifica Note
                                        </button>
                                        {/* Cancel/Uncancel button */}
                                        {project.is_cancelled ? (
                                            <button
                                                onClick={() => handleUncancel(project)}
                                                className="p-2 text-green-600 hover:bg-green-50 border border-green-200 rounded-lg transition-colors"
                                                title="Ripristina pratica"
                                            >
                                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6" />
                                                </svg>
                                            </button>
                                        ) : (
                                            <button
                                                onClick={() => handleCancel(project)}
                                                className="p-2 text-red-600 hover:bg-red-50 border border-red-200 rounded-lg transition-colors"
                                                title="Annulla pratica"
                                            >
                                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
                                                </svg>
                                            </button>
                                        )}
                                    </div>
                                </div>
                            </div>
                        );
                    })}
                </div>
            )}

            {/* Edit Project Modal */}
            {editingProject && (
                <UserEditProjectModal
                    project={editingProject}
                    onClose={() => setEditingProject(null)}
                    onSuccess={() => {
                        setEditingProject(null);
                        loadData();
                        toast('Pratica aggiornata con successo', 'success');
                    }}
                />
            )}

            {/* Timeline Modal */}
            {timelineProject && (
                <ProjectTimelineModal
                    project={timelineProject}
                    onClose={() => setTimelineProject(null)}
                    onStepChange={refreshProjectTimeline}
                    canEdit={true}
                    isAssigned={true}
                />
            )}

            {/* Confirmation Modal */}
            {confirmModal && (
                <ConfirmationModal
                    title={confirmModal.title}
                    message={confirmModal.message}
                    confirmText={confirmModal.confirmText}
                    variant={confirmModal.variant}
                    loading={confirmModal.loading}
                    onConfirm={executeConfirmedAction}
                    onCancel={() => setConfirmModal(null)}
                />
            )}
        </div>
    );
}

window.MyProjectsView = MyProjectsView;
