Spaces:
Running
Running
File size: 17,555 Bytes
f287aeb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 | 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<File | null>(null);
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
const [analysis, setAnalysis] = useState<AIPredictResponse | null>(null);
const [report, setReport] = useState<AutomatedHealthReport | null>(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 (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[88vh] overflow-hidden sm:max-w-6xl">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Stethoscope className="h-5 w-5 text-[#088395]" />
AI Health Check
</DialogTitle>
<DialogDescription>
Upload a fish image, generate a fixed robot report, then save it to
the selected batch in {tank?.name || "this tank"}.
</DialogDescription>
</DialogHeader>
<div className="grid gap-6 lg:grid-cols-[430px_minmax(0,640px)] lg:items-start lg:justify-start">
<div className="space-y-4">
<div className="rounded-lg border border-slate-200 bg-slate-50 p-4">
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2 md:col-span-2">
<Label htmlFor="health-batch">Batch</Label>
<Select
value={selectedBatchId}
onValueChange={setSelectedBatchId}
>
<SelectTrigger id="health-batch">
<SelectValue placeholder="Select batch" />
</SelectTrigger>
<SelectContent>
{tankBatches.map((batch) => (
<SelectItem key={batch.id} value={batch.id}>
{getBatchLabel(batch)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
<Input
id="health-ai-image"
type="file"
accept="image/*"
className="hidden"
onChange={(event) =>
setSelectedFile(event.target.files?.[0] || null)
}
/>
<div className="grid w-fit grid-cols-2 gap-3">
<div className="space-y-2">
<div className="flex items-center justify-between gap-2">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">
Original image
</p>
{previewUrl && (
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 px-2 text-xs text-[#0A4D68]"
onClick={() =>
setExpandedImage({
src: previewUrl,
title: "Original fish image",
})
}
>
Preview
</Button>
)}
</div>
<div className="h-44 w-44 overflow-hidden rounded-lg border border-slate-200 bg-slate-50 sm:h-52 sm:w-52">
{previewUrl ? (
<button
type="button"
className="relative h-full w-full cursor-zoom-in overflow-hidden"
onClick={() =>
setExpandedImage({
src: previewUrl,
title: "Original fish image",
})
}
>
<img
src={previewUrl}
alt="Fish preview"
className="h-full w-full object-contain p-2"
/>
<span className="absolute bottom-2 left-2 rounded-md bg-slate-900/75 px-2 py-1 text-[10px] font-medium text-white">
Show below
</span>
</button>
) : (
<label
htmlFor="health-ai-image"
className="flex h-full w-full cursor-pointer flex-col items-center justify-center p-3 text-center transition-colors hover:bg-[#F4FBFC]"
>
<ImagePlus className="mb-3 h-10 w-10 text-slate-400" />
<p className="text-sm font-semibold text-slate-800">
Upload image
</p>
<p className="mt-1 text-xs text-slate-500">
Stays inside this square
</p>
</label>
)}
</div>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between gap-2">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">
AI output
</p>
{annotatedImageSrc && (
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 px-2 text-xs text-[#0A4D68]"
onClick={() =>
setExpandedImage({
src: annotatedImageSrc,
title: "Annotated AI output",
})
}
>
Preview
</Button>
)}
</div>
<div className="h-44 w-44 overflow-hidden rounded-lg border border-slate-200 bg-slate-50 sm:h-52 sm:w-52">
{annotatedImageSrc ? (
<button
type="button"
className="relative h-full w-full cursor-zoom-in overflow-hidden"
onClick={() =>
setExpandedImage({
src: annotatedImageSrc,
title: "Annotated AI output",
})
}
>
<img
src={annotatedImageSrc}
alt="Annotated result"
className="h-full w-full object-contain p-2"
/>
<span className="absolute bottom-2 left-2 rounded-md bg-slate-900/75 px-2 py-1 text-[10px] font-medium text-white">
Show below
</span>
</button>
) : (
<div className="flex h-full w-full flex-col items-center justify-center p-3 text-center">
<Bot className="mb-3 h-10 w-10 text-slate-300" />
<p className="text-sm font-semibold text-slate-700">
AI result
</p>
<p className="mt-1 text-xs text-slate-500">
Appears here after analysis
</p>
</div>
)}
</div>
</div>
</div>
<div className="flex w-fit flex-wrap gap-2">
<Button asChild variant="outline">
<label htmlFor="health-ai-image" className="cursor-pointer">
{previewUrl ? "Change Image" : "Choose Image"}
</label>
</Button>
<Button
className="bg-[#088395] hover:bg-[#0A4D68]"
onClick={handleAnalyze}
disabled={!selectedFile || isAnalyzing}
>
{isAnalyzing ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Sparkles className="mr-2 h-4 w-4" />
)}
Run AI Check
</Button>
<Button
variant="outline"
onClick={() => {
setSelectedFile(null);
setAnalysis(null);
setReport(null);
}}
>
Reset
</Button>
</div>
{expandedImage && (
<div className="w-full max-w-[430px] overflow-hidden rounded-lg border border-slate-200 bg-white p-3">
<div className="mb-2 flex items-center justify-between gap-2">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">
{expandedImage.title}
</p>
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 px-2 text-xs"
onClick={() => setExpandedImage(null)}
>
Hide
</Button>
</div>
<div className="flex h-[320px] items-center justify-center overflow-auto rounded-lg bg-slate-50">
<img
src={expandedImage.src}
alt={expandedImage.title}
className="max-h-[300px] w-auto max-w-full object-contain p-2"
/>
</div>
</div>
)}
</div>
<div className="min-w-0 max-w-[640px] space-y-4">
<div className="rounded-lg border border-[#D7E9EE] bg-white p-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<p className="text-sm font-semibold text-slate-900">
Selected save target
</p>
<p className="text-sm text-slate-500">
{tank?.name || "No tank selected"}
{selectedBatch ? ` • ${getBatchLabel(selectedBatch)}` : ""}
</p>
</div>
{report && (
<Badge className="bg-[#0A4D68] text-white">
{report.topPredictionDisplay}
</Badge>
)}
</div>
</div>
<div className="max-h-[58vh] overflow-y-auto pr-1">
{report ? (
<>
{!report.isKnownClassification && (
<div className="rounded-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800">
{report.saveBlockedReason ||
"Unknown AI results are displayed for review only and cannot be saved to history."}
</div>
)}
{report.isKnownClassification && (
<RobotHealthReport
template={report.template}
healthStatus={report.mappedHealthStatus}
confidencePercent={report.confidencePercent}
checkedAt={report.payload.checkedAt}
batchLabel={
selectedBatch ? getBatchLabel(selectedBatch) : undefined
}
topPredictionLabel={report.topPredictionDisplay}
title="Fixed AI Health Report"
compact
libraryRecommendation={report.libraryRecommendation}
requireLibraryRecommendation={report.diseaseDetected}
/>
)}
<DialogFooter>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
>
Cancel
</Button>
<Button
className="bg-[#088395] hover:bg-[#0A4D68]"
onClick={handleSave}
disabled={isSaving || !report.isKnownClassification}
>
{isSaving ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Stethoscope className="mr-2 h-4 w-4" />
)}
Save Health Report
</Button>
</DialogFooter>
</>
) : (
<div className="flex min-h-[320px] flex-col items-center justify-center rounded-lg border border-dashed border-slate-300 bg-slate-50 p-8 text-center">
<Bot className="mb-4 h-14 w-14 text-slate-400" />
<p className="text-base font-semibold text-slate-800">
No report generated yet
</p>
<p className="mt-2 max-w-md text-sm text-slate-500">
The AI output will be transformed into a locked report based
on the disease template and saved directly to batch health
history.
</p>
</div>
)}
</div>
</div>
</div>
</DialogContent>
</Dialog>
);
}
|