import { useRef, useState } from 'react' import { FileUp, Library, Trash2 } from 'lucide-react' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' import { Button } from '@/components/ui/button' import { Dialog } from '@/components/ui/dialog' import { Field } from '@/components/ui/field' import { Input } from '@/components/ui/input' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table' import { EmptyState, ErrorState } from '@/components/page-states' import { ListSkeleton, RefreshingIndicator } from '@/components/page-skeleton' import { ApiError } from '@/lib/api' import { useCreateUpload, useDeleteUpload, useUploads, useRetention, usePlan } from '@/lib/queries' import { formatPlanBytes, primaryFilesError } from '@/lib/plan-limits' import { formatDateTime } from '@/lib/utils' import type { Upload } from '@/lib/types' export function FileLibrary() { const [filters, setFilters] = useState({ search: '', from: '', to: '' }) const [offset, setOffset] = useState(0) const dateProblem = filters.from && filters.to && filters.from > filters.to ? 'The covered date from must be on or before the covered date to.' : null // The management library includes unknown date spans; the comparison // picker's stricter known-dates behavior remains its existing default. const library = useUploads(filters.search, filters.from, filters.to, !dateProblem, offset, false) const create = useCreateUpload() const retention = useRetention() const plan = usePlan() const remove = useDeleteUpload() const [file, setFile] = useState(null) const [description, setDescription] = useState('') const [inputVersion, setInputVersion] = useState(0) const [problem, setProblem] = useState(null) const [uncertain, setUncertain] = useState(false) const [notice, setNotice] = useState('') const [deleting, setDeleting] = useState(null) const [deleteProblem, setDeleteProblem] = useState(null) const uploading = useRef(false) const deletingNow = useRef(false) const changeFilter = (key: keyof typeof filters, value: string) => { setFilters(current => ({ ...current, [key]: value })); setOffset(0) } const upload = async (event: React.FormEvent) => { event.preventDefault() if (uploading.current || uncertain) return setProblem(null); setNotice('') if (!file) { setProblem('Choose one file to store.'); return } const preflight = primaryFilesError([file], plan.data) if (preflight) { setProblem(preflight); return } uploading.current = true try { await create.mutateAsync({ file, source: 'manual', description: description.trim() }) setFile(null); setDescription(''); setInputVersion(value => value + 1); setOffset(0) setNotice('File stored in the library. No check was started.') } catch (error) { const unknownResult = error instanceof ApiError && (error.kind === 'network' || (error.status !== null && error.status >= 500)) setUncertain(unknownResult) setProblem(`${error instanceof Error ? error.message : String(error)}${unknownResult ? ' The file may already have been stored. Refresh the library and check for it before uploading again.' : ''}`) } finally { uploading.current = false } } const refresh = async () => { if (dateProblem) return const result = await library.refetch() if (!result.error) setUncertain(false) } const deleteFile = async () => { if (!deleting || deletingNow.current) return deletingNow.current = true; setDeleteProblem(null) try { await remove.mutateAsync(deleting.id) setDeleting(null); setOffset(0); setNotice('File removed from the library. Saved checks and accepted check usage are unchanged.') } catch (error) { setDeleteProblem(error instanceof Error ? error.message : String(error)) } finally { deletingNow.current = false } } return One library for manual check files and files added directly. Identical retained content is reused; adding a file does not run a check.
void upload(event)}>
{control => setFile(event.target.files?.[0] ?? null)} />} {control => setDescription(event.target.value)} placeholder="For example: March comparison export" />}

Library uploads and inspections alone do not use checks. Selecting Library files for an accepted analysis uses one check regardless of primary file count. Technical file and processing safety limits still apply. Add comparison history with the baseline picker in Check Charges. Deleting a file does not refund an accepted check.

{problem &&

{problem}

}
{uncertain && }

{retention.data?.retention_days === -1 ? 'Library files have no automatic expiry under the Owner plan. Keep your own backup.' : retention.data?.retention_days != null ? `Library files are retained for ${retention.data.retention_days} days from upload, under your current plan. After expiry, their source files are removed and history depending on them may become unavailable. Keep your own copy.` : 'Library files follow your plan retention policy. The current retention window is unavailable; no expiry date is assumed. Keep your own copy.'}

{control => changeFilter('search', event.target.value)} />} {control => changeFilter('from', event.target.value)} />} {control => changeFilter('to', event.target.value)} />}

Date filters match a file's covered period, not when it was uploaded. Files with unknown dates remain listed.

{dateProblem ? null : library.error ? void refresh()} isRetrying={library.isFetching} /> : library.isPending ? : !library.data?.length ? : <>{['File', 'Size', 'Covered period', 'Description / source', 'Stored', 'Actions'].map(label => {label})}{library.data.map(item => {item.filename}{item.row_count == null ? 'Row count unavailable' : `${item.row_count.toLocaleString()} rows`} {formatPlanBytes(item.size_bytes)} {item.min_date && item.max_date ? `${item.min_date} – ${item.max_date}` : 'Dates unavailable'} {item.description || 'No description'}{item.origins?.length ? item.origins.map(origin => origin === 'library' ? 'Added to Library' : 'Manual check file').join(' · ') : item.source === 's3_sync' ? 'Automatic AWS file' : 'Previously stored file'}{item.source === 'baseline_only' ? ' · Comparison / baseline' : ''} {formatDateTime(item.created_at)} )}
} {library.pagination && !dateProblem &&

{library.pagination.total === 0 ? '0 files' : `Files ${library.pagination.offset + 1}–${library.pagination.offset + library.pagination.returned} of ${library.pagination.total}`}

} {notice &&

{notice}

}
{ if (!remove.isPending && !open) setDeleting(null) }} title="Delete library file?" description={`Remove ${deleting?.filename ?? 'this file'}? Completed findings and reports remain; usage is not refunded. In-use files cannot be deleted.`}> {deleteProblem &&

{deleteProblem}

}
}