import { useEffect, useMemo, useState } from "react"; import { Bot, CheckCircle2, ImagePlus, Loader2, RotateCcw, Save, Sparkles, Stethoscope, X, } from "lucide-react"; import { toast } from "sonner"; import { Badge } from "../ui/badge"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; 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 InlineHealthCheckPanelProps { tankName?: string; tankBatches: any[]; batchId?: string; onClose?: () => void; onSuccess?: () => void; } const getBatchLabel = (batch: any) => batch?.batchNumber ? `Batch ${batch.batchNumber}` : `Batch ${String(batch?.id || "").slice(0, 8)}`; export function InlineHealthCheckPanel({ tankName, tankBatches, batchId, onClose, onSuccess, }: InlineHealthCheckPanelProps) { 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(() => { setSelectedBatchId(defaultBatchId); }, [defaultBatchId]); 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 hasImage = Boolean(selectedFile && previewUrl); const canSaveReport = Boolean(report?.isKnownClassification); const resetAll = () => { setSelectedFile(null); setAnalysis(null); setReport(null); setExpandedImage(null); }; 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); setAnalysis(result); setReport(await buildAutomatedHealthReportWithLibrary(result)); 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."); resetAll(); onSuccess?.(); } catch (error) { toast.error((error as Error).message); } finally { setIsSaving(false); } }; return (
AI Health Check

{tankName || "Tank"}{" "} {selectedBatch ? `- ${getBatchLabel(selectedBatch)}` : ""}

Select the batch, upload a fish image, then save the verified report.

{onClose && ( )}
{[ [ "1", "Target batch", selectedBatch ? getBatchLabel(selectedBatch) : "Not selected", ], ["2", "Image check", hasImage ? "Image ready" : "Waiting image"], ["3", "Report", report ? "Ready to review" : "Not generated"], ].map(([step, label, value]) => (
{step}

{label}

{value}

))}

The report will be saved under this batch history.

setSelectedFile(event.target.files?.[0] || null) } />

Fish image

{hasImage && ( Ready )}
{previewUrl ? ( ) : ( )}
{expandedImage && (

{expandedImage.title}

{expandedImage.title}
)}

AI output

{analysis && ( {report?.topPredictionDisplay || "Analyzed"} )}
{annotatedImageSrc ? ( ) : (

Run AI to show output

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

Report will appear here

Results, health library match, treatment actions, and save button stay in one place.

)}
); }