import React, { useRef, useState } from 'react'; import { Camera, Upload, Loader2 } from 'lucide-react'; import { usePhotoUpload } from '@/hooks/usePhotoUpload'; import { toast } from 'react-hot-toast'; interface ItemPhotoUploadProps { itemId: number; onUploadSuccess: (photo: { thumbnail_url: string; full_url: string; uploaded_at: string }) => void; onError: (errorMessage: string) => void; } export default function ItemPhotoUpload({ itemId, onUploadSuccess, onError, }: ItemPhotoUploadProps) { const { upload, isLoading, error } = usePhotoUpload(); const fileInputRef = useRef(null); const cameraInputRef = useRef(null); const [localError, setLocalError] = useState(null); const toastIdRef = useRef(null); // Sync hook error to local state for display React.useEffect(() => { if (error) { setLocalError(error); } }, [error]); // Cleanup: dismiss pending toasts on unmount React.useEffect(() => { return () => { if (toastIdRef.current) { toast.dismiss(toastIdRef.current); } }; }, []); const handleFileSelect = async (file: File) => { setLocalError(null); if (!file) return; toastIdRef.current = toast.loading('Uploading...'); try { const photo = await upload(file, itemId); toast.success('Photo uploaded successfully', { id: toastIdRef.current }); toastIdRef.current = null; onUploadSuccess(photo); // Reset file inputs if (fileInputRef.current) { fileInputRef.current.value = ''; } if (cameraInputRef.current) { cameraInputRef.current.value = ''; } } catch (err: any) { const errorMsg = err.message || 'Upload failed'; setLocalError(errorMsg); toast.error(errorMsg, { id: toastIdRef.current || undefined }); toastIdRef.current = null; onError(errorMsg); } }; const handleFileInputChange = (e: React.ChangeEvent) => { const files = e.target.files; if (files && files.length > 0) { handleFileSelect(files[0]); } }; const handleCameraCapture = (e: React.ChangeEvent) => { const files = e.target.files; if (files && files.length > 0) { handleFileSelect(files[0]); } }; const triggerFileInput = () => { fileInputRef.current?.click(); }; const triggerCameraInput = () => { cameraInputRef.current?.click(); }; return (
{/* Hidden file inputs */} {/* Button group */}
{/* File upload button */} {/* Camera button (mobile) */}
{/* Status messages */} {isLoading && (
Uploading...
)} {localError && (
{localError}
)}
); }