'use client' import { CircleAlertIcon, FileIcon, UploadIcon, VideoIcon } from 'lucide-react' import { useRouter } from 'next/navigation' import { useEffect, useRef, useState, type ChangeEvent } from 'react' import type { RecordingUploadResponse } from '@/app/(campaign)/campanha/(app)/comunicacao/acervo/gravacoes/types' import { Alert, AlertDescription } from '@/components/ui/Alert' import { Button } from '@/components/ui/button' import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from '@/components/ui/dialog' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Spinner } from '@/components/ui/Spinner' import { CAMPAIGN_RECORDING_UPLOAD_HREF } from '@/lib/campaignPaths' import { formatRecordingFileSize, RECORDING_FILE_REQUIRED_MESSAGE, RECORDING_FILE_TYPE_MESSAGE, RECORDING_MAX_BYTES, RECORDING_MAX_SIZE_LABEL, RECORDING_TITLE_MAX_LENGTH, RECORDING_TITLE_REQUIRED_MESSAGE, recordingFileTypeAllowed, recordingTooLargeMessage, } from '@/lib/recording' import { cn } from '@/lib/utils' const GENERIC_ERROR_MESSAGE = 'Não foi possível enviar a gravação. Tente novamente.' type UploadPhase = 'idle' | 'uploading' | 'error' type RecordingUploadDialogProps = { /** Layout of the trigger ("Enviar gravação" in the header and the empty state). */ triggerClassName?: string triggerVariant?: 'default' | 'outline' triggerLabel?: string /** Icon-only triggers (mobile header row) still need an accessible name. */ triggerAriaLabel?: string } /** * C199 — the one upload surface of the recordings source. Sends the RAW file * with XHR (real `upload.onprogress`, no server-action buffer) with the metadata * in the query string; the dialog stays open and unclosable while the file is * in flight, per the approved design. */ export const RecordingUploadDialog = ({ triggerClassName, triggerVariant = 'default', triggerLabel = 'Enviar gravação', triggerAriaLabel, }: RecordingUploadDialogProps) => { const router = useRouter() const fileInputRef = useRef(null) const xhrRef = useRef(null) const [open, setOpen] = useState(false) const [file, setFile] = useState(null) const [title, setTitle] = useState('') const [recordedAt, setRecordedAt] = useState('') const [phase, setPhase] = useState('idle') const [progress, setProgress] = useState(0) const [fileError, setFileError] = useState(null) const [titleError, setTitleError] = useState(null) const [error, setError] = useState(null) const uploading = phase === 'uploading' // Navigating away unmounts the dialog: abort the in-flight XHR instead of // leaving an invisible multi-GB upload running (the reaper cleans a row left // in `uploading` by a crash). useEffect( () => () => { xhrRef.current?.abort() xhrRef.current = null }, [], ) const reset = () => { setFile(null) setTitle('') setRecordedAt('') setPhase('idle') setProgress(0) setFileError(null) setTitleError(null) setError(null) if (fileInputRef.current) fileInputRef.current.value = '' } const onFileChange = (event: ChangeEvent) => { const next = event.target.files?.[0] ?? null setFileError(null) if (!next) { setFile(null) return } // The refused file stays visible with its name/size; the error below the // picker explains the refusal and blocks the submit (approved scene 10). setFile(next) if (!recordingFileTypeAllowed(next.type)) { setFileError(RECORDING_FILE_TYPE_MESSAGE) return } if (next.size > RECORDING_MAX_BYTES) { setFileError(recordingTooLargeMessage(next.size)) } } const submit = () => { const nextTitle = title.trim() setTitleError(null) setError(null) if (!file) { setFileError(RECORDING_FILE_REQUIRED_MESSAGE) return } if (fileError) return if (!nextTitle) { setTitleError(RECORDING_TITLE_REQUIRED_MESSAGE) return } const params = new URLSearchParams({ title: nextTitle, filename: file.name }) if (recordedAt) params.set('recordedAt', recordedAt) const xhr = new XMLHttpRequest() xhrRef.current = xhr setPhase('uploading') setProgress(0) xhr.open('POST', `${CAMPAIGN_RECORDING_UPLOAD_HREF}?${params.toString()}`) xhr.setRequestHeader('Accept', 'application/json') xhr.upload.addEventListener('progress', (event) => { if (event.lengthComputable && event.total > 0) { setProgress(Math.round((event.loaded / event.total) * 100)) } }) xhr.addEventListener('load', () => { xhrRef.current = null try { const payload = JSON.parse(xhr.responseText) as RecordingUploadResponse if (xhr.status >= 200 && xhr.status < 300 && payload.status === 'success') { reset() setOpen(false) router.refresh() return } setPhase('error') setError(payload.status === 'error' ? payload.message : GENERIC_ERROR_MESSAGE) } catch { setPhase('error') setError(GENERIC_ERROR_MESSAGE) } }) xhr.addEventListener('error', () => { xhrRef.current = null setPhase('error') setError(GENERIC_ERROR_MESSAGE) }) xhr.send(file) } return ( { if (uploading) return setOpen(next) if (!next) reset() }} > { if (uploading) event.preventDefault() }} onEscapeKeyDown={(event) => { if (uploading) event.preventDefault() }} > {/* The frontend prose base styles every `h2` with a bottom border; the approved dialog header is a single block (scene 4). */} {uploading ? 'Enviando gravação' : 'Enviar gravação'} {uploading ? 'Mantenha esta janela aberta até concluir.' : 'Adicione um arquivo local ao acervo.'} {uploading ? (

{file?.name}

{title.trim()} {recordedAt ? ` · ${recordedAt.split('-').reverse().join('/')}` : ''}

{progress}%
Enviando arquivo… {progress}%

Quando o envio terminar, a gravação aparecerá na lista como “Processando”.

) : (
{fileError ? ( <>

Vídeos até {RECORDING_MAX_SIZE_LABEL} · MP4, MOV, MKV e formatos compatíveis

) : null}
{ setTitle(event.target.value) if (titleError) setTitleError(null) }} placeholder="Título da gravação" className="mt-1.5 min-h-11" aria-invalid={titleError ? true : undefined} /> {titleError ? (

{titleError}

) : null}
setRecordedAt(event.target.value)} className="mt-1.5 min-h-11" />
)} {error ? ( ) : null} {uploading ? ( ) : ( <> )}
) }