import { useEffect, useMemo } from "react";
import { useMutation } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Sparkles, TrendingUp, AlertTriangle, Info, Loader2 } from "lucide-react";
import { analyticsService, type AiInsightItem } from "@/services/analytics.service";
import { useToast } from "@/hooks/use-toast";

const EMPTY_PAYLOAD: Record<string, unknown> = {};

function insightIcon(severity: AiInsightItem["severity"]) {
  switch (severity) {
    case "critical":
      return AlertTriangle;
    case "warning":
      return TrendingUp;
    default:
      return Info;
  }
}

function insightColor(severity: AiInsightItem["severity"]) {
  switch (severity) {
    case "critical":
      return "text-destructive";
    case "warning":
      return "text-warning";
    default:
      return "text-primary";
  }
}

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

export default function AiInsightsPanel({ data = EMPTY_PAYLOAD }: Props) {
  const { toast } = useToast();
  const payloadKey = useMemo(() => JSON.stringify(data), [data]);

  const mutation = useMutation({
    mutationFn: (payload: Record<string, unknown>) => analyticsService.getInsights(payload),
    onError: (err: Error) => {
      toast({
        title: "Insights unavailable",
        description: err.message || "Could not load AI insights.",
        variant: "destructive",
      });
    },
  });

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

  const items = mutation.data?.insights ?? [];

  return (
    <Card className="border-0 shadow-sm">
      <CardHeader className="pb-3">
        <CardTitle className="text-base font-semibold flex items-center gap-2">
          <Sparkles className="h-4 w-4 text-primary" />
          AI Platform Insights
        </CardTitle>
      </CardHeader>
      <CardContent>
        {mutation.isPending && (
          <div className="flex items-center gap-2 text-sm text-muted-foreground py-8 justify-center">
            <Loader2 className="h-5 w-5 animate-spin text-primary" />
            Loading insights…
          </div>
        )}
        {mutation.isError && !mutation.isPending && (
          <p className="text-sm text-muted-foreground py-4 text-center">Could not load insights.</p>
        )}
        {mutation.isSuccess && items.length === 0 && (
          <p className="text-sm text-muted-foreground py-4 text-center">No insights available for this view.</p>
        )}
        {!mutation.isPending && items.length > 0 && (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {items.map((item, idx) => {
              const Icon = insightIcon(item.severity);
              const color = insightColor(item.severity);
              return (
                <div key={idx} className="rounded-lg border bg-muted/30 p-4">
                  <div className="flex items-center gap-2 mb-2">
                    <Icon className={`h-4 w-4 ${color}`} />
                    <span className="text-sm font-semibold">{item.title}</span>
                  </div>
                  <p className="text-sm text-muted-foreground">{item.description}</p>
                  {item.recommendation && (
                    <p className="text-xs text-muted-foreground mt-2 italic">
                      {item.recommendation}
                    </p>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </CardContent>
    </Card>
  );
}
