"use client";

/**
 * Post-final pipeline indicator — shows, on the case, whether the two automatic
 * steps (voice learning + halacha extraction) ran, succeeded, why not, and how many
 * halachot were extracted. Rendered in the drafts panel's "החלטה סופית של היו״ר"
 * section, below the run buttons. Read-only; derives from db.case_learning_status.
 */

import { Brain, Scale } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import {
  useCaseLearningStatus,
  type VoiceLearningStatus,
  type HalachaExtractionStatus,
} from "@/lib/api/learning";

type Tone = "ok" | "danger" | "warn" | "info" | "muted";

const TONE_CLASS: Record<Tone, string> = {
  ok: "bg-success-bg text-success border-success/40",
  danger: "bg-danger-bg text-danger border-danger/40",
  warn: "bg-warn-bg text-warn border-warn/40",
  info: "bg-info-bg text-info border-info/40",
  muted: "bg-rule-soft text-ink-muted border-rule",
};

function voiceView(v: VoiceLearningStatus): {
  tone: Tone;
  label: string;
  sub: string;
} {
  if (v.outcome === "succeeded") {
    const bits = [`${v.lessons_count} לקחים הופקו`];
    if (v.style_corpus_enrolled) bits.push("נרשם לקורפוס-הסגנון");
    if (v.lessons_proposed > 0) bits.push(`${v.lessons_proposed} הוצעו לאישור`);
    return { tone: "ok", label: "הצליח", sub: bits.join(" · ") };
  }
  if (v.outcome === "failed") {
    return {
      tone: "danger",
      label: "נכשל",
      sub: v.error ? `הריצה נכשלה: ${v.error}` : "הריצה נכשלה",
    };
  }
  return {
    tone: "muted",
    label: "טרם בוצע",
    sub: 'הרץ "למידת-קול" כדי להפיק לקחים מההשוואה טיוטה↔סופי',
  };
}

const HALACHA_LABEL: Record<string, string> = {
  completed: "הושלם",
  processing: "רץ עכשיו",
  pending: "בתור",
  busy: "ממתין לתור",
  partial: "חלקי",
  failed: "נכשל",
  extraction_failed: "נכשל",
  no_chunks: "אין טקסט לחילוץ",
};

function halachaView(h: HalachaExtractionStatus): {
  tone: Tone;
  label: string;
  sub: string;
} {
  if (!h.enrolled_in_corpus) {
    return {
      tone: "danger",
      label: "לא נכנס לקורפוס",
      sub:
        h.not_enrolled_reason ??
        "ההחלטה הסופית טרם נכנסה לקורפוס-הפסיקה הפנימי — אין ממה לחלץ הלכות",
    };
  }
  const counts = `חולצו ${h.halachot_count} הלכות · ${h.approved} אושרו · ${h.pending} ממתינות · ${h.rejected} נדחו`;
  switch (h.status) {
    case "completed":
      return { tone: "ok", label: "הושלם", sub: counts };
    case "processing":
    case "pending":
    case "busy":
      return {
        tone: "info",
        label: HALACHA_LABEL[h.status],
        sub: 'ממתין לעיבוד — הרץ "אימות-הלכות" אם טרם הופעל',
      };
    case "partial":
      return {
        tone: "warn",
        label: "חלקי",
        sub: `חלק מהקטעים נכשלו — חולצו ${h.halachot_count} הלכות`,
      };
    case "no_chunks":
      return {
        tone: "warn",
        label: "אין טקסט לחילוץ",
        sub: "לא נמצא טקסט מתאים בהחלטה לחילוץ הלכות",
      };
    case "failed":
    case "extraction_failed":
      return {
        tone: "danger",
        label: "נכשל",
        sub: "חילוץ ההלכות נכשל — ראה דף התפעול",
      };
    default:
      return { tone: "muted", label: "טרם בוצע", sub: counts };
  }
}

function Row({
  icon,
  name,
  tone,
  label,
  sub,
}: {
  icon: React.ReactNode;
  name: string;
  tone: Tone;
  label: string;
  sub: string;
}) {
  return (
    <div className="flex items-start gap-3">
      <span className="flex h-[30px] w-[30px] shrink-0 items-center justify-center rounded-md border border-rule bg-gold-wash text-gold-deep">
        {icon}
      </span>
      <div className="min-w-0 flex-1">
        <div className="flex flex-wrap items-center gap-2">
          <span className="text-navy text-sm font-semibold">{name}</span>
          <Badge className={`text-[0.65rem] ${TONE_CLASS[tone]}`}>{label}</Badge>
        </div>
        <p className="text-ink-muted mt-0.5 text-xs leading-relaxed tabular-nums">
          {sub}
        </p>
      </div>
    </div>
  );
}

export function LearningStatusBadges({ caseNumber }: { caseNumber: string }) {
  const { data } = useCaseLearningStatus(caseNumber);
  if (!data) return null;

  const v = voiceView(data.voice_learning);
  const h = halachaView(data.halacha_extraction);

  return (
    <div className="border-rule-soft mt-4 flex flex-col gap-3 border-t pt-3.5">
      <Row
        icon={<Brain className="h-4 w-4" />}
        name="למידת-קול"
        tone={v.tone}
        label={v.label}
        sub={v.sub}
      />
      <Row
        icon={<Scale className="h-4 w-4" />}
        name="חילוץ-הלכות"
        tone={h.tone}
        label={h.label}
        sub={h.sub}
      />
    </div>
  );
}
