"use client";

import { useTranslations } from "next-intl";

import type { AwoooPStatusChain } from "@/components/awooop/status-chain";
import { cn } from "@/lib/utils";

type AutomationAssetTone = "ready" | "pending" | "blocked";

export interface AutomationAssetRemediationSummary {
  has_mcp_investigation?: boolean | null;
  latest_route?: string | null;
}

function assetToneClass(tone: AutomationAssetTone) {
  if (tone === "ready") return "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]";
  if (tone === "blocked") return "border-[#e2a29b] bg-[#fff0ef] text-[#9f2f25]";
  return "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]";
}

function countLabel(value: number) {
  return value > 0 ? String(value) : "--";
}

function valueLabel(value: number, fallback: string) {
  return value > 0 ? String(value) : fallback;
}

function nextActionLabel(value: unknown, labels: Record<string, string>, fallback: string) {
  const key = String(value ?? "");
  return labels[key] ?? (value ? String(value) : fallback);
}

export function AwoooPAutomationAssetLedger({
  chain,
  remediationSummary,
  showDetails = false,
  className,
}: {
  chain?: AwoooPStatusChain | null;
  remediationSummary?: AutomationAssetRemediationSummary | null;
  showDetails?: boolean;
  className?: string;
}) {
  const t = useTranslations("awooop.automationAssetLedger");
  const nextActionLabels: Record<string, string> = {
    open_apply_gate_work_item_review_verifier_and_km: t("nextActions.openApplyGateWorkItem"),
    owner_review_apply_gate_or_create_verifier_plan: t("nextActions.openApplyGateWorkItem"),
    owner_review_repair_candidate_draft: t("nextActions.ownerReviewRepairCandidateDraft"),
    manual_review_no_action_decision: t("nextActions.manualReviewNoActionDecision"),
  };
  const handoff = chain?.automation_handoff;
  const handoffAssets = handoff?.asset_ids;
  const kmCount = chain?.evidence?.knowledge_entries ?? 0;
  const playbookCount = (chain?.execution?.playbook_ids?.length ?? 0)
    + (chain?.execution?.playbook_paths?.length ?? 0);
  const ansible = chain?.execution?.ansible;
  const ansibleCandidates = ansible?.candidate_count ?? 0;
  const dryRunCount = (ansible?.check_mode_total ?? 0) + (ansible?.pending_check_mode_total ?? 0);
  const applyCount = ansible?.apply_total ?? 0;
  const ansibleDryRunOnly = Boolean(chain?.evidence?.ansible_dry_run_only)
    || (
      dryRunCount > 0
      && applyCount === 0
      && ansible?.applied !== true
      && ansible?.controlled_apply !== true
    );
  const correlation = chain?.source_refs?.correlation;
  const scheduleCount = (correlation?.provider_event_total ?? 0)
    + (correlation?.direct_ref_total ?? 0)
    + (correlation?.candidate_total ?? 0)
    + (correlation?.applied_link_total ?? 0);
  const verification = String(chain?.verification ?? "").toLowerCase();
  const verifierReady = verification.includes("verified") || verification.includes("success");
  const verifierBlocked = verification.includes("degraded") || verification.includes("fail");
  const route = String(remediationSummary?.latest_route ?? chain?.evidence?.latest_route ?? "");
  const noRepairCandidate = route.includes("fallback")
    || route.includes("no_action")
    || chain?.blockers?.some((item) => item.includes("playbook") || item.includes("candidate"));

  const items = [
    {
      key: "km",
      tone: kmCount > 0 ? "ready" : "pending",
      value: countLabel(kmCount),
    },
    {
      key: "playbook",
      tone: playbookCount > 0 ? "ready" : noRepairCandidate ? "blocked" : "pending",
      value: countLabel(playbookCount),
    },
    {
      key: "dryRun",
      tone: dryRunCount > 0
        ? "ready"
        : ansibleCandidates > 0
          ? "pending"
          : "blocked",
      value: valueLabel(dryRunCount, ansibleCandidates > 0 ? t("values.pending") : "--"),
    },
    {
      key: "apply",
      tone: applyCount > 0 || ansible?.applied === true
        ? "ready"
        : dryRunCount > 0 || ansibleCandidates > 0 || ansibleDryRunOnly || chain?.needs_human
            ? "pending"
            : "blocked",
      value: applyCount > 0 ? String(applyCount) : ansible?.applied === true ? t("values.ready") : t("values.notApplied"),
    },
    {
      key: "schedule",
      tone: scheduleCount > 0 ? "ready" : "pending",
      value: countLabel(scheduleCount),
    },
    {
      key: "verifier",
      tone: verifierReady ? "ready" : verifierBlocked || ansibleDryRunOnly ? "blocked" : "pending",
      value: verifierReady ? t("values.ready") : verifierBlocked || ansibleDryRunOnly ? t("values.blocked") : t("values.pending"),
    },
  ] satisfies Array<{ key: string; tone: AutomationAssetTone; value: string }>;
  const readyCount = items.filter((item) => item.tone === "ready").length;
  const blockedCount = items.filter((item) => item.tone === "blocked").length;
  const detailItems = [
    { key: "workItem", value: handoff?.work_item_id },
    { key: "dryRun", value: handoffAssets?.dry_run },
    { key: "apply", value: handoffAssets?.apply_candidate },
    { key: "verifier", value: handoffAssets?.verifier },
    {
      key: "nextStep",
      value: nextActionLabel(handoff?.next_action ?? chain?.next_step, nextActionLabels, "--"),
    },
  ].filter((item) => Boolean(item.value));

  return (
    <div className={cn("min-w-[260px] border border-[#e0ddd4] bg-white p-2", className)}>
      <div className="flex flex-wrap items-center justify-between gap-2">
        <span className="text-xs font-semibold text-[#141413]">{t("title")}</span>
        <span className={cn(
          "border px-2 py-0.5 font-mono text-[11px] font-semibold",
          blockedCount > 0
            ? "border-[#e2a29b] bg-[#fff0ef] text-[#9f2f25]"
            : "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]"
        )}>
          {t("summary", { ready: readyCount, blocked: blockedCount })}
        </span>
      </div>
      <div className="mt-2 grid grid-cols-2 gap-1.5">
        {items.map((item) => (
          <div key={item.key} className={cn("min-w-0 border px-2 py-1", assetToneClass(item.tone))}>
            <div className="flex items-center justify-between gap-2">
              <span className="truncate text-[11px] font-semibold">{t(`items.${item.key}` as never)}</span>
              <span className="font-mono text-[11px] font-semibold">{item.value}</span>
            </div>
          </div>
        ))}
      </div>
      <p className="mt-2 text-[11px] leading-5 text-[#77736a]">
        {t("boundary")}
      </p>
      {showDetails && detailItems.length > 0 && (
        <div className="mt-2 border-t border-[#eee9dd] pt-2">
          <p className="text-[11px] font-semibold text-[#141413]">{t("detailsTitle")}</p>
          <dl className="mt-2 space-y-1.5">
            {detailItems.map((item) => (
              <div key={item.key} className="min-w-0">
                <dt className="text-[10px] font-semibold uppercase tracking-[0.08em] text-[#9a968c]">
                  {t(`details.${item.key}` as never)}
                </dt>
                <dd className="mt-0.5 break-all font-mono text-[11px] leading-4 text-[#141413]">
                  {String(item.value)}
                </dd>
              </div>
            ))}
          </dl>
        </div>
      )}
    </div>
  );
}
