"use client"; import React, { useState, useEffect } from 'react'; import { Folder, FileText, Upload, FolderPlus, Trash2, Loader2, ChevronRight } from 'lucide-react'; interface MissionFile { type: 'folder' | 'file'; name: string; path: string; key: string; size?: number; lastModified?: string; } interface MissionUser { role: string; userId: string; } interface Mission { id: string; name: string; creatorId: string; isClosed?: boolean; missionUsers?: MissionUser[]; } interface MissionFilesManagerProps { mission: Mission; currentUserId: string; currentPath?: string; onFileSelect?: (file: MissionFile) => void; selectedFileKey?: string; } export const MissionFilesManager: React.FC = ({ mission, currentUserId, currentPath = 'attachments', onFileSelect, selectedFileKey }) => { const [files, setFiles] = useState([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const [isUploading, setIsUploading] = useState(false); const [newFolderName, setNewFolderName] = useState(''); const [showNewFolder, setShowNewFolder] = useState(false); // Check user permissions const isCreator = mission.creatorId === currentUserId; const userRole = mission.missionUsers?.find(mu => mu.userId === currentUserId)?.role; const isGardien = userRole === 'gardien-temps' || userRole === 'gardien-parole' || userRole === 'gardien-memoire'; const isClosed = mission.isClosed || false; const canManage = (isCreator || isGardien) && !isClosed; // Cannot manage if mission is closed const fetchFiles = async () => { try { setIsLoading(true); setError(null); const url = `/api/missions/${mission.id}/files${currentPath ? `?path=${encodeURIComponent(currentPath)}` : ''}`; const response = await fetch(url); if (!response.ok) { throw new Error('Failed to fetch files'); } const data = await response.json(); // API returns { folders: [], files: [] } or { files: [] } setFiles(data.files || []); } catch (err) { console.error('Error fetching mission files:', err); setError(err instanceof Error ? err.message : 'Failed to load files'); } finally { setIsLoading(false); } }; useEffect(() => { if (!mission.id) return; fetchFiles(); }, [mission.id, currentPath]); const handleFileUpload = async (event: React.ChangeEvent) => { const file = event.target.files?.[0]; if (!file || !canManage) return; try { setIsUploading(true); const formData = new FormData(); formData.append('file', file); formData.append('missionId', mission.id); formData.append('path', currentPath); const response = await fetch(`/api/missions/${mission.id}/files/upload`, { method: 'POST', body: formData }); if (!response.ok) { const errorData = await response.json().catch(() => ({})); const errorMessage = errorData.details || errorData.error || 'Failed to upload file'; throw new Error(errorMessage); } // Refresh file list await fetchFiles(); } catch (err) { console.error('Error uploading file:', err); setError(err instanceof Error ? err.message : 'Failed to upload file'); } finally { setIsUploading(false); // Reset input event.target.value = ''; } }; const handleCreateFolder = async () => { if (!newFolderName.trim() || !canManage) return; try { setIsLoading(true); const folderPath = currentPath ? `${currentPath}/${newFolderName}` : newFolderName; const response = await fetch(`/api/missions/${mission.id}/files/folder`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: folderPath }) }); if (!response.ok) { throw new Error('Failed to create folder'); } // Refresh file list await fetchFiles(); setNewFolderName(''); setShowNewFolder(false); } catch (err) { console.error('Error creating folder:', err); setError(err instanceof Error ? err.message : 'Failed to create folder'); } finally { setIsLoading(false); } }; const handleDelete = async (file: MissionFile) => { if (!canManage || !confirm(`Êtes-vous sûr de vouloir supprimer ${file.name} ?`)) return; try { const response = await fetch(`/api/missions/${mission.id}/files`, { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: file.key }) }); if (!response.ok) { throw new Error('Failed to delete'); } // Refresh file list await fetchFiles(); } catch (err) { console.error('Error deleting file:', err); setError(err instanceof Error ? err.message : 'Failed to delete'); } }; if (isLoading) { return (
); } if (error) { return (

Erreur

{error}

); } return (

{currentPath || 'Fichiers'}

{canManage && (
)}
{showNewFolder && canManage && (
setNewFolderName(e.target.value)} onKeyPress={(e) => e.key === 'Enter' && handleCreateFolder()} placeholder="Nom du dossier" className="flex-1 px-3 py-2 border border-carnet-border rounded-md text-sm text-carnet-text-primary bg-white focus:outline-none focus:ring-1 focus:ring-primary" />
)}
{files.length === 0 ? (

Aucun fichier

) : (
    {files.map((file) => { const Icon = file.type === 'folder' ? Folder : FileText; return (
  • onFileSelect?.(file)} > {file.name} {file.type === 'folder' && ( )}
    {canManage && ( )}
  • ); })}
)}
{isUploading && (
Upload en cours...
)}
); };