'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useRef } from 'react';
import { X, Upload, Search, ImageIcon, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { cmsApi } from '../lib/api.js';
import { useApiData } from '../lib/useApiData.js';
export function MediaPickerModal({ open, onClose, onSelect, onSelectItem, accept, libraryOnly = false, }) {
    const [tab, setTab] = useState('library');
    const [search, setSearch] = useState('');
    const [uploading, setUploading] = useState(false);
    const fileInputRef = useRef(null);
    const { data, loading, refetch } = useApiData(open ? `/media?pageSize=50${search ? `&search=${encodeURIComponent(search)}` : ''}` : null);
    const items = data?.data?.items ?? data?.items ?? [];
    const imageItems = items.filter((item) => item.mimeType.startsWith('image/'));
    async function handleUpload(files) {
        if (!files || files.length === 0)
            return;
        setUploading(true);
        const file = files[0];
        const formData = new FormData();
        formData.append('file', file);
        const res = await cmsApi('/media/upload', {
            method: 'POST',
            body: formData,
        });
        if (res.error) {
            toast.error(res.error);
        }
        else if (res.data) {
            const mediaItem = res.data;
            const url = mediaItem.url || mediaItem.storageKey || '';
            toast.success(`Uploaded ${file.name}`);
            onSelectItem?.({
                id: mediaItem.id,
                storageKey: mediaItem.storageKey,
                url,
                filename: mediaItem.filename ?? file.name,
                mimeType: mediaItem.mimeType ?? file.type,
                width: mediaItem.width,
                height: mediaItem.height,
            });
            onSelect(url, file.name);
            onClose();
        }
        setUploading(false);
        if (fileInputRef.current)
            fileInputRef.current.value = '';
    }
    function handleSelectItem(item) {
        const url = item.url || item.storageKey || '';
        onSelectItem?.({
            id: item.id,
            storageKey: item.storageKey,
            url,
            filename: item.filename,
            mimeType: item.mimeType,
            width: item.width,
            height: item.height,
        });
        onSelect(url, item.filename);
        onClose();
    }
    if (!open)
        return null;
    return (_jsxs("div", { className: "fixed inset-0 z-50 flex items-center justify-center", children: [_jsx("div", { className: "fixed inset-0 bg-black/40", onClick: onClose }), _jsxs("div", { className: "relative mx-4 flex max-h-[80vh] w-full max-w-2xl flex-col rounded-xl bg-white shadow-2xl", children: [_jsxs("div", { className: "flex items-center justify-between border-b border-gray-200 px-4 py-3", children: [_jsx("h2", { className: "text-lg font-semibold text-gray-900", children: "Insert Image" }), _jsx("button", { onClick: onClose, className: "rounded-lg p-1.5 transition-colors hover:bg-gray-100", children: _jsx(X, { className: "h-5 w-5 text-gray-500" }) })] }), !libraryOnly && (_jsxs("div", { className: "flex border-b border-gray-200", children: [_jsx("button", { onClick: () => setTab('library'), className: `flex-1 px-4 py-2.5 text-sm font-medium transition-colors ${tab === 'library'
                                    ? 'border-b-2 border-blue-600 text-blue-600'
                                    : 'text-gray-500 hover:text-gray-700'}`, children: "Media Library" }), _jsx("button", { onClick: () => setTab('upload'), className: `flex-1 px-4 py-2.5 text-sm font-medium transition-colors ${tab === 'upload'
                                    ? 'border-b-2 border-blue-600 text-blue-600'
                                    : 'text-gray-500 hover:text-gray-700'}`, children: "Upload New" })] })), _jsx("div", { className: "flex-1 overflow-y-auto p-4", children: libraryOnly || tab === 'library' ? (_jsxs(_Fragment, { children: [_jsxs("div", { className: "relative mb-4", children: [_jsx(Search, { className: "absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-gray-400" }), _jsx("input", { type: "text", value: search, onChange: (e) => setSearch(e.target.value), placeholder: "Search images...", className: "w-full rounded-lg border border-gray-300 py-2 pr-3 pl-9 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none" })] }), loading ? (_jsx("div", { className: "flex items-center justify-center py-12", children: _jsx(Loader2, { className: "h-6 w-6 animate-spin text-gray-400" }) })) : imageItems.length === 0 ? (_jsx("div", { className: "py-12 text-center text-sm text-gray-500", children: "No images found. Try uploading one." })) : (_jsx("div", { className: "grid grid-cols-3 gap-3 sm:grid-cols-4", children: imageItems.map((item) => {
                                        const src = item.url || item.storageKey;
                                        return (_jsxs("button", { onClick: () => handleSelectItem(item), title: item.filename, className: "group relative aspect-square overflow-hidden rounded-lg border-2 border-gray-200 bg-gray-100 transition-colors hover:border-blue-500", children: [src ? (_jsx("img", { src: src, alt: item.filename, loading: "lazy", className: "h-full w-full object-contain" })) : (_jsx("div", { className: "flex h-full w-full items-center justify-center", children: _jsx(ImageIcon, { className: "h-8 w-8 text-gray-300" }) })), _jsx("div", { className: "absolute inset-x-0 bottom-0 bg-black/60 p-1.5 opacity-0 transition-opacity group-hover:opacity-100", children: _jsx("p", { className: "truncate text-xs text-white", children: item.filename }) })] }, item.id));
                                    }) }))] })) : (_jsxs("div", { className: "flex flex-col items-center justify-center py-12", children: [_jsx("input", { ref: fileInputRef, type: "file", accept: accept ?? 'image/*', className: "hidden", onChange: (e) => handleUpload(e.target.files) }), _jsx("div", { className: "mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-blue-50", children: uploading ? (_jsx(Loader2, { className: "h-8 w-8 animate-spin text-blue-600" })) : (_jsx(Upload, { className: "h-8 w-8 text-blue-600" })) }), _jsx("p", { className: "mb-4 text-sm text-gray-600", children: uploading ? 'Uploading...' : 'Select an image file to upload' }), !uploading && (_jsx("button", { onClick: () => fileInputRef.current?.click(), className: "rounded-lg bg-blue-600 px-4 py-2 text-sm text-white transition-colors hover:bg-blue-700", children: "Choose File" }))] })) })] })] }));
}
//# sourceMappingURL=MediaPickerModal.js.map