import React, { useState, useRef } from 'react'; import { Upload, X, Image, Loader2 } from 'lucide-react'; import { Button } from '../common'; import { clsx } from 'clsx'; import { api } from '../../config/api'; import { toast } from 'react-toastify'; import { useQuery } from '@tanstack/react-query'; import { categoriesService } from '../../services/categories.service'; import { useTranslation } from 'react-i18next'; interface PhotoUploadProps { eventId: number; onUploadComplete?: () => void; } export const PhotoUpload: React.FC = ({ eventId, onUploadComplete }) => { const { t } = useTranslation(); const [isUploading, setIsUploading] = useState(false); const [selectedFiles, setSelectedFiles] = useState([]); const [uploadProgress, setUploadProgress] = useState(0); const [currentChunk, setCurrentChunk] = useState(0); const [totalChunks, setTotalChunks] = useState(0); const [selectedCategoryId, setSelectedCategoryId] = useState(null); const fileInputRef = useRef(null); // Fetch categories for this event const { data: categories = [] } = useQuery({ queryKey: ['event-categories', eventId], queryFn: () => categoriesService.getEventCategories(eventId), }); const handleFileSelect = (e: React.ChangeEvent) => { const files = Array.from(e.target.files || []); const imageFiles = files.filter(file => ['image/jpeg', 'image/png', 'image/webp'].includes(file.type) ); // Check total file count with existing files const totalFiles = selectedFiles.length + imageFiles.length; if (totalFiles > 500) { const allowedNewFiles = 500 - selectedFiles.length; if (allowedNewFiles <= 0) { toast.error(t('upload.maxFilesReached') || 'Maximum 500 files allowed'); return; } toast.warning(t('upload.someFilesSkipped') || `Only ${allowedNewFiles} more files can be added (500 max)`); setSelectedFiles(prev => [...prev, ...imageFiles.slice(0, allowedNewFiles)]); return; } setSelectedFiles(prev => [...prev, ...imageFiles]); }; const removeFile = (index: number) => { setSelectedFiles(prev => prev.filter((_, i) => i !== index)); }; const handleUpload = async () => { if (selectedFiles.length === 0) return; // Validate file count if (selectedFiles.length > 500) { toast.error(t('upload.tooManyFiles') || 'Maximum 500 files can be uploaded at once'); return; } setIsUploading(true); setUploadProgress(0); // For large uploads, chunk the files to prevent memory issues const CHUNK_SIZE = 50; // Upload 50 files at a time const chunks = []; for (let i = 0; i < selectedFiles.length; i += CHUNK_SIZE) { chunks.push(selectedFiles.slice(i, i + CHUNK_SIZE)); } setTotalChunks(chunks.length); let totalUploaded = 0; let failedFiles = []; try { for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) { setCurrentChunk(chunkIndex + 1); const chunk = chunks[chunkIndex]; const formData = new FormData(); chunk.forEach((file) => { formData.append('photos', file); }); if (selectedCategoryId) { formData.append('category_id', selectedCategoryId.toString()); } try { const response = await api.post(`/admin/events/${eventId}/upload`, formData, { onUploadProgress: (progressEvent) => { if (progressEvent.total) { // Calculate overall progress across all chunks const chunkProgress = progressEvent.loaded / progressEvent.total; const overallProgress = ((chunkIndex + chunkProgress) / chunks.length) * 100; setUploadProgress(Math.round(overallProgress)); } }, }); totalUploaded += chunk.length; } catch (error: any) { console.error(`Error uploading chunk ${chunkIndex + 1}:`, error); failedFiles.push(...chunk.map(f => f.name)); // Continue with next chunk even if one fails continue; } } // Clear selected files setSelectedFiles([]); if (fileInputRef.current) { fileInputRef.current.value = ''; } // Show appropriate message if (failedFiles.length === 0) { toast.success(t('upload.uploadComplete') || `Successfully uploaded ${totalUploaded} files`); } else { toast.warning( t('upload.someFilesFailed') || `Uploaded ${totalUploaded} files. ${failedFiles.length} files failed.` ); } // Call callback if (onUploadComplete) { onUploadComplete(); } } catch (error: any) { console.error('Upload error:', error); toast.error(error.response?.data?.error || t('toast.uploadError')); } finally { setIsUploading(false); setUploadProgress(0); setCurrentChunk(0); setTotalChunks(0); } }; const formatFileSize = (bytes: number) => { if (bytes < 1024) return bytes + ' B'; if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'; return (bytes / (1024 * 1024)).toFixed(1) + ' MB'; }; return (
{/* Category Selection */}
{/* File Input Area */}
0 ? "border-primary-400 bg-primary-50/30" : "border-neutral-300" )} onClick={() => fileInputRef.current?.click()} >

{t('upload.clickToUpload')}

{t('upload.fileRequirements')}

{/* Selected Files */} {selectedFiles.length > 0 && (

{t('upload.selectedFiles')} ({selectedFiles.length})

{selectedFiles.map((file, index) => (

{file.name}

{formatFileSize(file.size)}

))}
)} {/* Upload Button */}
{/* Progress Bar */} {isUploading && (
{t('upload.uploading')} {totalChunks > 1 && ` (${t('common.chunk')} ${currentChunk}/${totalChunks})`} {uploadProgress}%
{totalChunks > 1 && (

{t('upload.uploadingChunks', { count: selectedFiles.length, total: totalChunks })}

)}
)}
); }; PhotoUpload.displayName = 'PhotoUpload';