import { useEffect, useMemo, useState } from "react"; import { Bot, ImagePlus, Loader2, Sparkles, Stethoscope } from "lucide-react"; import { toast } from "sonner"; import { Badge } from "../../ui/badge"; import { Button } from "../../ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "../../ui/dialog"; import { Input } from "../../ui/input"; import { Label } from "../../ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "../../ui/select"; import { AIPredictResponse, AutomatedHealthReport, buildAutomatedHealthReportWithLibrary, getAnnotatedImageSrc, predictFishDisease, } from "../../../services/aiDetectionApi"; import { createHealthCheck } from "../../../services/healthCheckApi"; import { RobotHealthReport } from "../../health/RobotHealthReport"; interface HealthCheckModalProps { open: boolean; onOpenChange: (open: boolean) => void; tank: any; tankBatches: any[]; batchId?: string; onSuccess?: () => void; } const getBatchLabel = (batch: any) => batch?.batchNumber ? `Batch ${batch.batchNumber}` : `Batch ${String(batch?.id || "").slice(0, 8)}`; export function HealthCheckModal({ open, onOpenChange, tank, tankBatches, batchId, onSuccess, }: HealthCheckModalProps) { const defaultBatchId = useMemo( () => batchId || tankBatches[0]?.id || "", [batchId, tankBatches], ); const [selectedBatchId, setSelectedBatchId] = useState(defaultBatchId); const [selectedFile, setSelectedFile] = useState(null); const [previewUrl, setPreviewUrl] = useState(null); const [analysis, setAnalysis] = useState(null); const [report, setReport] = useState(null); const [isAnalyzing, setIsAnalyzing] = useState(false); const [isSaving, setIsSaving] = useState(false); const [expandedImage, setExpandedImage] = useState<{ src: string; title: string; } | null>(null); useEffect(() => { if (!open) return; setSelectedBatchId(defaultBatchId); setSelectedFile(null); setPreviewUrl(null); setAnalysis(null); setReport(null); setExpandedImage(null); }, [defaultBatchId, open]); useEffect(() => { if (!selectedFile) { setPreviewUrl(null); return; } const objectUrl = URL.createObjectURL(selectedFile); setPreviewUrl(objectUrl); return () => URL.revokeObjectURL(objectUrl); }, [selectedFile]); const selectedBatch = tankBatches.find((batch) => batch.id === selectedBatchId) || null; const annotatedImageSrc = getAnnotatedImageSrc(analysis); const handleAnalyze = async () => { if (!selectedFile) { toast.error("Choose a fish image before running the AI check."); return; } setIsAnalyzing(true); try { const result = await predictFishDisease(selectedFile); const automatedReport = await buildAutomatedHealthReportWithLibrary(result); setAnalysis(result); setReport(automatedReport); toast.success("AI report generated."); } catch (error) { toast.error((error as Error).message); } finally { setIsAnalyzing(false); } }; const handleSave = async () => { if (!selectedBatchId) { toast.error("Select a batch before saving the health report."); return; } if (!report) { toast.error("Run the AI check first."); return; } if (!report.isKnownClassification) { toast.error( report.saveBlockedReason || "Unknown AI results cannot be saved to history.", ); return; } setIsSaving(true); try { await createHealthCheck(selectedBatchId, { batchId: selectedBatchId, healthStatus: report.payload.healthStatus!, checkType: report.payload.checkType || "TARGETED", bacterialType: report.payload.bacterialType, bacterialLoadPercentage: report.payload.bacterialLoadPercentage, treatmentSuggestion: report.payload.treatmentSuggestion, feedingAdvice: report.payload.feedingAdvice, checkedAt: report.payload.checkedAt, medicineId: report.payload.medicineId || undefined, }); toast.success("Health report saved to batch history."); onOpenChange(false); onSuccess?.(); } catch (error) { toast.error((error as Error).message); } finally { setIsSaving(false); } }; return ( AI Health Check Upload a fish image, generate a fixed robot report, then save it to the selected batch in {tank?.name || "this tank"}.
setSelectedFile(event.target.files?.[0] || null) } />

Original image

{previewUrl && ( )}
{previewUrl ? ( ) : ( )}

AI output

{annotatedImageSrc && ( )}
{annotatedImageSrc ? ( ) : (

AI result

Appears here after analysis

)}
{expandedImage && (

{expandedImage.title}

{expandedImage.title}
)}

Selected save target

{tank?.name || "No tank selected"} {selectedBatch ? ` • ${getBatchLabel(selectedBatch)}` : ""}

{report && ( {report.topPredictionDisplay} )}
{report ? ( <> {!report.isKnownClassification && (
{report.saveBlockedReason || "Unknown AI results are displayed for review only and cannot be saved to history."}
)} {report.isKnownClassification && ( )} ) : (

No report generated yet

The AI output will be transformed into a locked report based on the disease template and saved directly to batch health history.

)}
); }