import { useRef, useState, type DragEvent } from 'react'; import { Alert, Box, Button, CircularProgress, IconButton, Link, Stack, Typography } from '@mui/material'; import UploadFileIcon from '@mui/icons-material/UploadFile'; import DeleteIcon from '@mui/icons-material/Delete'; import { useT } from '../../i18n'; import { ACCEPT_ATTR, attachmentUrl, checkFile, uploadAttachment, type PendingFile, type StoredAttachment, } from '../../api/attachments'; const isImage = (a: StoredAttachment) => /\.(png|jpe?g|webp|bmp)$/i.test(a.FILE_NAME.trim()); /** One attachment slot (legacy: one Dropzone). It holds a stored file, a pending upload, or neither. */ export function AttachmentField(props: { field: string; label: string; required: boolean; error?: string; readOnly?: boolean; stored?: StoredAttachment; baseUrl: string; maxMb: number; pending?: PendingFile; onPending: (p: PendingFile | undefined) => void; onDeleteStored?: (a: StoredAttachment) => void; }) { const { field, label, required, error, readOnly, stored, baseUrl, maxMb, pending, onPending, onDeleteStored } = props; const t = useT(); const input = useRef(null); const [busy, setBusy] = useState(false); const [err, setErr] = useState(''); const [over, setOver] = useState(false); const [broken, setBroken] = useState(false); const pick = async (file?: File) => { if (!file) return; const bad = checkFile(file, maxMb); if (bad) return setErr(t(bad)); setErr(''); setBusy(true); try { onPending({ fileType: field, file: await uploadAttachment(file), name: file.name }); } catch (e) { setErr(t(e instanceof Error ? e.message : 'UPLOAD_ATTACHMENT_ERROR')); } finally { setBusy(false); if (input.current) input.current.value = ''; } }; const onDrop = (e: DragEvent) => { e.preventDefault(); setOver(false); if (!readOnly) void pick(e.dataTransfer.files[0]); }; const shown = pending ? null : stored; const problem = err || error; return ( { e.preventDefault(); setOver(true); }} onDragLeave={() => setOver(false)} onDrop={onDrop} sx={{ border: '2px dashed', borderColor: problem ? 'error.main' : over ? 'primary.main' : 'divider', borderRadius: 2, p: 1.5, minHeight: 130, bgcolor: over ? 'action.selected' : 'action.hover', }} > {label} {required ? ' *' : ''} {shown && ( {isImage(shown) && !broken ? ( setBroken(true)} sx={{ height: 64, borderRadius: 1, display: 'block' }} /> ) : ( {shown.FILE_NAME.trim()} )} {!readOnly && onDeleteStored && ( onDeleteStored(shown)} aria-label={t('DELETE')}> )} )} {pending && ( {pending.name} onPending(undefined)} aria-label={t('DELETE')}> )} {!readOnly && ( <> void pick(e.target.files?.[0])} /> )} {problem && {problem}} ); }