import { useEffect, useMemo } from "react";
import { useMutation } from "@tanstack/react-query";
import { Sparkles, Loader2 } from "lucide-react";
import { analyticsService } from "@/services/analytics.service";
import { useToast } from "@/hooks/use-toast";

interface Props {
  report_type: string;
  data: Record<string, unknown>;
}

export default function AiReportNarrative({ report_type, data }: Props) {
  const { toast } = useToast();
  const dataKey = useMemo(() => JSON.stringify(data), [data]);

  const mutation = useMutation({
    mutationFn: (vars: { report_type: string; data: Record<string, unknown> }) =>
      analyticsService.getReportNarrative(vars),
    onError: (err: Error) => {
      toast({
        title: "Summary unavailable",
        description: err.message || "Could not generate AI summary.",
        variant: "destructive",
      });
    },
  });

  useEffect(() => {
    mutation.mutate({ report_type, data });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [report_type, dataKey]);

  return (
    <div className="rounded-lg border bg-primary/5 p-4 mb-4 flex items-start gap-3">
      <Sparkles className="h-4 w-4 text-primary shrink-0 mt-0.5" />
      <div className="flex-1 min-w-0">
        <span className="text-xs font-semibold text-primary">AI Summary</span>
        {mutation.isPending && (
          <p className="text-sm text-muted-foreground mt-1 flex items-center gap-2">
            <Loader2 className="h-4 w-4 animate-spin shrink-0" />
            Generating summary…
          </p>
        )}
        {mutation.isError && !mutation.isPending && (
          <p className="text-sm text-muted-foreground mt-1">Could not load summary.</p>
        )}
        {!mutation.isPending && mutation.data?.narrative && (
          <p className="text-sm text-muted-foreground mt-1">{mutation.data.narrative}</p>
        )}
        {mutation.isSuccess && !mutation.data?.narrative?.trim() && (
          <p className="text-sm text-muted-foreground mt-1">No summary returned.</p>
        )}
      </div>
    </div>
  );
}
