import { useQuery } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { getIntelligenceBrief } from "@/lib/ai.functions";
import { GlassCard, SectionLabel } from "@/components/GlassCard";
import { AlertTriangle, CheckCircle2, Info, Flame, Compass } from "lucide-react";

const severityStyle: Record<string, { ring: string; text: string; Icon: any }> = {
  info: { ring: "border-electric/25 bg-electric/5", text: "text-electric", Icon: Info },
  success: { ring: "border-success/25 bg-success/5", text: "text-success", Icon: CheckCircle2 },
  warning: { ring: "border-warning/25 bg-warning/5", text: "text-warning", Icon: AlertTriangle },
  critical: { ring: "border-destructive/30 bg-destructive/5", text: "text-destructive", Icon: Flame },
};

/** Deterministic, number-backed alerts and the single next best action. */
export function IntelligencePanel() {
  const fn = useServerFn(getIntelligenceBrief);
  const q = useQuery({
    queryKey: ["intelligence-brief"],
    queryFn: () => fn(),
    staleTime: 60_000,
  });

  const alerts = q.data?.alerts ?? [];
  const next = q.data?.nextAction ?? null;
  if (!q.data) return null;

  return (
    <section className="space-y-3">
      <SectionLabel>What needs your attention</SectionLabel>

      {next && (
        <GlassCard className="p-4">
          <div className="flex items-start gap-3">
            <div className="size-9 rounded-xl bg-gradient-to-br from-electric to-purple grid place-items-center shrink-0">
              <Compass className="size-4 text-primary-foreground" />
            </div>
            <div className="min-w-0">
              <p className="text-[10px] uppercase tracking-widest text-muted-foreground">Next best action</p>
              <p className="text-sm font-medium mt-1">{next.title}</p>
              <p className="text-[11px] text-muted-foreground mt-1.5 leading-relaxed">{next.why}</p>
              <p className="text-[11px] text-electric mt-1">{next.effect}</p>
            </div>
          </div>
        </GlassCard>
      )}

      {alerts.map((a) => {
        const s = severityStyle[a.severity] ?? severityStyle.info;
        return (
          <div key={a.key} className={`rounded-2xl border p-4 ${s.ring}`}>
            <div className="flex items-start gap-2.5">
              <s.Icon className={`size-4 mt-0.5 shrink-0 ${s.text}`} />
              <div className="min-w-0">
                <p className="text-sm font-medium">{a.title}</p>
                <p className="text-[11px] text-muted-foreground mt-1 leading-relaxed">{a.body}</p>
                {a.action && <p className="text-[11px] text-foreground/80 mt-1.5">{a.action}</p>}
              </div>
            </div>
          </div>
        );
      })}
    </section>
  );
}
