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",
      });
    },
  });

  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 handleApply = () => {
    toast({ title: "Suggestion Applied", description: "Batch split recommendation has been saved successfully." });
    setOpen(false);
  };

  const onOpenChange = (next: boolean) => {
    setOpen(next);
    if (!next) mutation.reset();
  };

  const suggestions = mutation.data ?? [];
  const showResults = !mutation.isPending && !mutation.isError && suggestions.length > 0;
  const showEmpty = !mutation.isPending && !mutation.isError && mutation.isSuccess && suggestions.length === 0;

  return (
    <>
      <Button variant="outline" size="sm" onClick={handleOpen}>
        <Sparkles className="h-3.5 w-3.5 mr-1 text-primary" /> AI Suggest Batch Split
      </Button>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Sparkles className="h-4 w-4 text-primary" /> AI Batch Optimization
            </DialogTitle>
          </DialogHeader>
          {mutation.isPending ? (
            <div className="flex items-center gap-2 text-sm text-muted-foreground py-6 justify-center">
              <Loader2 className="h-5 w-5 animate-spin text-primary" /> Analyzing batch data...
            </div>
          ) : mutation.isError ? (
            <p className="text-sm text-muted-foreground py-4 text-center">Something went wrong. Try again.</p>
          ) : showResults ? (
            <div className="space-y-4">
              <div className="space-y-3 max-h-[50vh] overflow-y-auto">
                {suggestions.map((s, i) => (
                  <div key={i} className="rounded-lg bg-muted/30 p-4 border border-border/60">
                    <p className="text-xs font-semibold text-primary uppercase tracking-wide mb-1">{s.impact} impact</p>
                    <p className="text-sm font-medium">{s.suggestion}</p>
                    {s.details ? <p className="text-sm text-muted-foreground mt-2 leading-relaxed">{s.details}</p> : null}
                  </div>
                ))}
              </div>
              <div className="flex gap-2">
                <Button className="flex-1" onClick={handleApply}>
                  Apply Suggestion
                </Button>
                <Button variant="outline" onClick={() => onOpenChange(false)}>
                  Dismiss
                </Button>
              </div>
            </div>
          ) : showEmpty ? (
            <p className="text-sm text-muted-foreground py-4 text-center">No optimization suggestions for this batch.</p>
          ) : null}
        </DialogContent>
      </Dialog>
    </>
  );
}
