'use client'; import { useState, useEffect, useRef } from 'react'; import { mediaApi, Media } from '@/lib/api'; import Button from '@/components/ui/Button'; import { PhotoIcon, ArrowUpTrayIcon, XMarkIcon, CheckIcon, FolderOpenIcon, } from '@heroicons/react/24/outline'; import toast from 'react-hot-toast'; interface MediaPickerProps { value?: string; onChange: (url: string) => void; relatedId?: string; relatedType?: string; } export default function MediaPicker({ value, onChange, relatedId, relatedType = 'event' }: MediaPickerProps) { const [showModal, setShowModal] = useState(false); const [activeTab, setActiveTab] = useState<'upload' | 'library'>('upload'); const [media, setMedia] = useState([]); const [loading, setLoading] = useState(false); const [uploading, setUploading] = useState(false); const [selectedMedia, setSelectedMedia] = useState(null); const fileInputRef = useRef(null); useEffect(() => { if (showModal && activeTab === 'library') { loadMedia(); } }, [showModal, activeTab]); const loadMedia = async () => { setLoading(true); try { const { media } = await mediaApi.getAll(); setMedia(media); } catch (error) { toast.error('Failed to load media library'); } finally { setLoading(false); } }; const handleUpload = async (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; setUploading(true); try { const result = await mediaApi.upload(file, relatedId, relatedType); onChange(result.url); toast.success('Image uploaded successfully'); setShowModal(false); } catch (error: any) { toast.error(error.message || 'Failed to upload image'); } finally { setUploading(false); if (fileInputRef.current) { fileInputRef.current.value = ''; } } }; const handleSelectFromLibrary = () => { if (selectedMedia) { onChange(selectedMedia); setShowModal(false); setSelectedMedia(null); } }; const handleRemove = () => { onChange(''); }; return (
{value ? (
Event banner
) : (
)}
{/* Media Library Modal */} {showModal && (
{/* Modal Header */}

Select Image

{/* Tabs */}
{/* Tab Content */}
{activeTab === 'upload' && (
fileInputRef.current?.click()} className="border-2 border-dashed border-secondary-light-gray rounded-btn p-12 text-center cursor-pointer hover:border-primary-yellow transition-colors" > {uploading ? (

Uploading...

) : (

Click to upload an image

JPEG, PNG, GIF, WebP (max 10MB)

)}
)} {activeTab === 'library' && ( <> {loading ? (
) : media.length === 0 ? (

No images in library

Upload an image to get started

) : (
{media.map((item) => ( ))}
)} )}
{/* Modal Footer */} {activeTab === 'library' && (
)}
)}
); }