import { useState } from "react"; import { useMutation } from "@tanstack/react-query"; import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Sparkles, Loader2 } from "lucide-react"; import { useToast } from "@/hooks/use-toast"; import { analyticsService } from "@/services/analytics.service"; interface Props { batchId?: number; } export default function AiBatchOptimizer({ batchId }: Props) { const [open, setOpen] = useState(false); const { toast } = useToast(); const mutation = useMutation({ mutationFn: (id: number) => analyticsService.getBatchOptimization(id), onError: (err: Error) => { toast({ title: "Optimization failed", description: err.message || "Could not analyze this batch.", variant: "destructive", }); }, }); type OptResult = Awaited>; const handleOpen = () => { if (batchId == null) { toast({ title: "No batch selected", description: "Choose a batch to analyze, or open this from a batch detail page.", variant: "destructive", }); return; } mutation.reset(); setOpen(true); mutation.mutate(batchId); }; const applyMutation = useMutation({ mutationFn: () => analyticsService.applyBatchOptimization(batchId!, mutation.data?.optimized ?? []), onSuccess: (res) => { toast({ title: "Suggestion Applied", description: `${res.applied} optimization(s) saved successfully.` }); setOpen(false); }, onError: (err: Error) => { toast({ variant: "destructive", title: "Apply failed", description: err.message || "Could not apply batch optimization.", }); }, }); const handleApply = () => { applyMutation.mutate(); }; const onOpenChange = (next: boolean) => { setOpen(next); if (!next) mutation.reset(); }; const optData = mutation.data as OptResult | undefined; const hasSuggestions = !!optData?.summary; const showResults = !mutation.isPending && !mutation.isError && hasSuggestions; const showEmpty = !mutation.isPending && !mutation.isError && mutation.isSuccess && !hasSuggestions; return ( <> AI Batch Optimization {mutation.isPending ? (
Analyzing batch data...
) : mutation.isError ? (

Something went wrong. Try again.

) : showResults && optData ? (

{optData.impact} impact

{optData.summary}

{Array.isArray(optData.optimized) && optData.optimized.length > 0 && (
{optData.optimized.map((item, i) => (
{typeof item === "object" && item !== null ? JSON.stringify(item) : String(item)}
))}
)}
) : showEmpty ? (

No optimization suggestions for this batch.

) : null}
); }