"use client"; import { useState, useRef } from "react"; import Image from "next/image"; import { useServiceManagement } from "@/lib/hooks/useServices"; interface ServiceImageUploadProps { serviceSlug: string; currentImageUrl?: string; onImageUploaded?: (service: any) => void; } const ServiceImageUpload: React.FC = ({ serviceSlug, currentImageUrl, onImageUploaded, }) => { const [selectedFile, setSelectedFile] = useState(null); const [previewUrl, setPreviewUrl] = useState(null); const [uploading, setUploading] = useState(false); const fileInputRef = useRef(null); const { uploadServiceImage, loading, error } = useServiceManagement(); const handleFileSelect = (event: React.ChangeEvent) => { const file = event.target.files?.[0]; if (file) { // Validate file type if (!file.type.startsWith('image/')) { alert('Please select an image file'); return; } // Validate file size (5MB limit) if (file.size > 5 * 1024 * 1024) { alert('File size must be less than 5MB'); return; } setSelectedFile(file); // Create preview URL const url = URL.createObjectURL(file); setPreviewUrl(url); } }; const handleUpload = async () => { if (!selectedFile) return; try { setUploading(true); const updatedService = await uploadServiceImage(serviceSlug, selectedFile); // Clean up preview URL if (previewUrl) { URL.revokeObjectURL(previewUrl); } setSelectedFile(null); setPreviewUrl(null); if (fileInputRef.current) { fileInputRef.current.value = ''; } if (onImageUploaded) { onImageUploaded(updatedService); } alert('Image uploaded successfully!'); } catch (err) { console.error('Upload failed:', err); alert('Failed to upload image. Please try again.'); } finally { setUploading(false); } }; const handleCancel = () => { setSelectedFile(null); if (previewUrl) { URL.revokeObjectURL(previewUrl); setPreviewUrl(null); } if (fileInputRef.current) { fileInputRef.current.value = ''; } }; return (
Select an image file (JPG, PNG, GIF). Maximum size: 5MB.
{/* Current Image */} {currentImageUrl && !previewUrl && (
Current service image
)} {/* Preview */} {previewUrl && (
Preview
)} {/* Error Display */} {error && (
{error}
)} {/* Action Buttons */} {selectedFile && (
)}
); }; export default ServiceImageUpload;