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<ReturnType<typeof analyticsService.getBatchOptimization>>;

  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 (
    <>
      <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 && optData ? (
            <div className="space-y-4">
              <div 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">{optData.impact} impact</p>
                <p className="text-sm font-medium">{optData.summary}</p>
              </div>
              {Array.isArray(optData.optimized) && optData.optimized.length > 0 && (
                <div className="space-y-2 max-h-[40vh] overflow-y-auto">
                  {optData.optimized.map((item, i) => (
                    <div key={i} className="rounded-lg bg-muted/20 p-3 border text-sm">
                      {typeof item === "object" && item !== null ? JSON.stringify(item) : String(item)}
                    </div>
                  ))}
                </div>
              )}
              <div className="flex gap-2">
                <Button className="flex-1" onClick={handleApply} disabled={applyMutation.isPending}>
                  {applyMutation.isPending ? (
                    <><Loader2 className="h-4 w-4 mr-2 animate-spin" /> Applying...</>
                  ) : (
                    "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>
    </>
  );
}
