'use client'; import { useState, useRef } from 'react'; import { Box, Avatar, IconButton, TextField, Typography, Paper, Alert, CircularProgress, } from '@mui/material'; import { PhotoCamera, Person } from '@mui/icons-material'; import { photosApi } from '@/lib/api/photos'; interface PhotoUploadProps { value: string; onChange: (url: string) => void; label: string; disabled?: boolean; size?: number; childId?: string; type?: string; } export function PhotoUpload({ value, onChange, label, disabled = false, size = 100, childId, type = 'profile' }: PhotoUploadProps) { const [imageError, setImageError] = useState(false); const [uploadError, setUploadError] = useState(''); const [uploading, setUploading] = useState(false); const fileInputRef = useRef(null); const handleImageError = () => { setImageError(true); }; const handleImageLoad = () => { setImageError(false); }; const handleFileSelect = async (event: React.ChangeEvent) => { const file = event.target.files?.[0]; if (!file) return; // Validate file type if (!file.type.startsWith('image/')) { setUploadError('Please select an image file'); return; } // Validate file size (max 10MB - backend limit) const maxSize = 10 * 1024 * 1024; // 10MB if (file.size > maxSize) { setUploadError('Image size must be less than 10MB'); return; } try { setUploading(true); setUploadError(''); // Upload to backend - it handles Sharp optimization and MinIO storage const result = await photosApi.uploadPhoto(file, { childId, type, }); // Use the optimized URL from backend onChange(result.photo.url); setImageError(false); } catch (error: any) { console.error('Photo upload failed:', error); setUploadError(error.response?.data?.message || 'Failed to upload photo'); } finally { setUploading(false); // Reset input if (fileInputRef.current) { fileInputRef.current.value = ''; } } }; const handleCameraClick = () => { fileInputRef.current?.click(); }; return ( {label} {uploadError && ( setUploadError('')} sx={{ width: '100%' }}> {uploadError} )} {!value || imageError ? : null} {uploading ? ( ) : ( )} onChange(e.target.value)} fullWidth size="small" placeholder="https://example.com/photo.jpg" disabled={disabled || uploading} helperText={ uploading ? 'Uploading and optimizing image...' : 'Click camera to upload (auto-optimized) or paste URL' } /> ); }