import { useRef, useState } from "react"; import { useQueryClient } from "@tanstack/react-query"; import { Download, FileSpreadsheet, Upload, CheckCircle2, AlertCircle, X, } from "lucide-react"; import type { BulkImportResult } from "@/api/assets"; import { ApiError } from "@/api/client"; import { Modal } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { toast } from "@/lib/toast"; import { cn } from "@/lib/utils"; export interface PreviewColumn { key: string; label: string; } interface BulkGenericImportModalProps { open: boolean; onClose: () => void; title: string; description: string; entityName: string; templateFilename: string; onDownloadTemplate: () => Promise; onImport: (file: File, dryRun: boolean, skipInvalid: boolean) => Promise; queryKeysToInvalidate: string[][]; previewColumns: PreviewColumn[]; } const ACCEPTED_EXTS = [".xlsx", ".xls", ".csv"]; export function BulkGenericImportModal({ open, onClose, title, description, entityName, templateFilename, onDownloadTemplate, onImport, queryKeysToInvalidate, previewColumns, }: BulkGenericImportModalProps) { const qc = useQueryClient(); const fileInputRef = useRef(null); const [selectedFile, setSelectedFile] = useState(null); const [dragActive, setDragActive] = useState(false); const [downloadingTemplate, setDownloadingTemplate] = useState(false); const [validating, setValidating] = useState(false); const [importing, setImporting] = useState(false); const [skipInvalid, setSkipInvalid] = useState(false); const [preview, setPreview] = useState(null); const [errorMsg, setErrorMsg] = useState(null); function resetState() { setSelectedFile(null); setPreview(null); setErrorMsg(null); setSkipInvalid(false); setValidating(false); setImporting(false); if (fileInputRef.current) fileInputRef.current.value = ""; } function handleClose() { if (importing) return; resetState(); onClose(); } async function handleDownloadTemplate() { setDownloadingTemplate(true); setErrorMsg(null); try { await onDownloadTemplate(); toast.success(`Downloaded ${templateFilename}`); } catch (err) { const msg = err instanceof ApiError ? err.detail : "Failed to download import template."; setErrorMsg(msg); toast.error(msg); } finally { setDownloadingTemplate(false); } } async function handleFileSelect(files: FileList | null) { if (!files || files.length === 0) return; const file = files[0]; const lower = file.name.toLowerCase(); if (!ACCEPTED_EXTS.some((ext) => lower.endsWith(ext))) { setErrorMsg("Unsupported file type. Please upload an .xlsx, .xls, or .csv file."); setSelectedFile(null); setPreview(null); return; } setSelectedFile(file); setErrorMsg(null); setPreview(null); setSkipInvalid(false); setValidating(true); try { const result = await onImport(file, true, false); setPreview(result); } catch (err) { const msg = err instanceof ApiError ? err.detail : "Failed to validate import file."; setErrorMsg(msg); } finally { setValidating(false); } } async function handleConfirmImport() { if (!selectedFile || !preview) return; setImporting(true); setErrorMsg(null); try { const result = await onImport(selectedFile, false, skipInvalid); await Promise.all( queryKeysToInvalidate.map((key) => qc.invalidateQueries({ queryKey: key })) ); toast.success( `Imported ${result.created_count} ${entityName.toLowerCase()}${ result.created_count === 1 ? "" : "s" }` ); resetState(); onClose(); } catch (err) { const msg = err instanceof ApiError ? err.detail : `Bulk ${entityName.toLowerCase()} import failed.`; setErrorMsg(msg); toast.error(msg); } finally { setImporting(false); } } const canImport = Boolean(selectedFile && preview) && !validating && !importing && preview!.valid_count > 0 && (preview!.error_count === 0 || skipInvalid); return ( { if (!next) handleClose(); }} title={title} description={description} className="max-w-4xl" >
{/* Step 1: Template Download */}
Step 1: Download the Excel Template

Download the official pre-formatted template with lookup references before uploading.

{/* Step 2: File Picker / Dropzone */}
{ e.preventDefault(); setDragActive(true); }} onDragLeave={() => setDragActive(false)} onDrop={(e) => { e.preventDefault(); setDragActive(false); void handleFileSelect(e.dataTransfer.files); }} className={cn( "border-2 border-dashed rounded-lg p-5 text-center transition-colors", dragActive ? "border-[#1e3a8a] bg-blue-50" : "border-gray-300 bg-gray-50/60 hover:bg-gray-50" )} > void handleFileSelect(e.target.files)} className="hidden" />

{selectedFile ? selectedFile.name : "Drop your spreadsheet here, or browse"}

Accepts .xlsx, .xls, or .csv — automatically validates rows before importing.

{selectedFile && ( )}
{validating && (
Validating rows against hospital masters...
)} {errorMsg && (
{errorMsg}
)} {/* Step 3: Dry-run Validation Preview */} {preview && (
Total Rows: {preview.total_rows} Valid: {preview.valid_count} 0 ? "bg-red-100 text-red-800 border-red-200" : "bg-gray-100 text-gray-600 border-gray-200" )} > Errors: {preview.error_count}
{preview.error_count > 0 && preview.valid_count > 0 && ( )}
{previewColumns.map((col) => ( ))} {preview.preview_rows.length === 0 ? ( ) : ( preview.preview_rows.map((r) => { const rowRecord = r as unknown as Record; const rowData = (rowRecord.data as Record | undefined) || rowRecord; return ( {previewColumns.map((col) => { const val = rowRecord[col.key] ?? rowData[col.key]; return ( ); })} ); }) )}
Row {col.label} Validation
No data rows found in spreadsheet.
{r.row} {val !== null && val !== undefined && val !== "" ? String(val) : "—"} {r.valid ? ( Ready ) : ( {r.error || "Invalid row"} )}
)} {/* Footer */}
); }