"use client";

import { ArrowRight, GitBranch, KeyRound, ListChecks, RefreshCw, SearchCheck, TriangleAlert } from "lucide-react";
import { useTranslations } from "next-intl";

import {
  AwoooPStatusChainPanel,
  type AwoooPStatusChain,
} from "@/components/awooop/status-chain";
import { Link } from "@/i18n/routing";
import type { IncidentTimelineResponse } from "@/lib/api-client";
import { cn } from "@/lib/utils";
import type { ApprovalRequest } from "@/stores/approval.store";

function uniqueValues(values: Array<string | null | undefined>) {
  return Array.from(new Set(values.filter((value): value is string => Boolean(value))));
}

function timelineStatusClass(status?: string | null) {
  if (status === "ok" || status === "success" || status === "completed") {
    return "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]";
  }
  if (status === "warn" || status === "warning" || status === "degraded") {
    return "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]";
  }
  if (status === "fail" || status === "failed" || status === "blocked") {
    return "border-[#e2a29b] bg-[#fff0ef] text-[#9f2f25]";
  }
  return "border-[#d8d3c7] bg-[#faf9f3] text-[#5f5b52]";
}

function idMatchesIncident(approval: ApprovalRequest, incidentId: string) {
  return approval.incident_id === incidentId;
}

function idMatchesApproval(approval: ApprovalRequest, approvalId?: string | null) {
  return Boolean(approvalId && approval.id === approvalId);
}

export function IncidentAuthorizationFocus({
  projectId,
  incidentId,
  approvalId,
  chain,
  timeline,
  pendingApprovals,
  loading,
  error,
}: {
  projectId: string;
  incidentId: string;
  approvalId?: string | null;
  chain: AwoooPStatusChain | null;
  timeline: IncidentTimelineResponse | null;
  pendingApprovals: ApprovalRequest[];
  loading: boolean;
  error: string | null;
}) {
  const t = useTranslations("authorizations.incidentFocus");
  const encodedProjectId = encodeURIComponent(projectId);
  const encodedIncidentId = encodeURIComponent(incidentId);
  const encodedApprovalId = approvalId ? encodeURIComponent(approvalId) : null;
  const incidentPendingMatches = pendingApprovals.filter((approval) => idMatchesIncident(approval, incidentId));
  const requestedApproval = pendingApprovals.find((approval) => idMatchesApproval(approval, approvalId));
  const timelineApprovalIds = timeline?.approval_ids ?? [];
  const linkedApprovalIds = uniqueValues([
    approvalId,
    ...timelineApprovalIds,
    ...incidentPendingMatches.map((approval) => approval.id),
  ]);
  const stages = timeline?.timeline?.filter((stage) => stage.status !== "skipped") ?? [];
  const verifier = timeline?.timeline?.find((stage) => stage.stage === "verifier");
  const executor = timeline?.timeline?.find((stage) => stage.stage === "executor");
  const km = timeline?.timeline?.find((stage) => stage.stage === "km");
  const ansible = chain?.execution?.ansible;
  const outcome = chain?.operator_outcome;
  const needsHuman = chain?.needs_human ?? outcome?.needs_human ?? false;
  const topMcpTool = chain?.mcp?.top_tools?.[0]?.tool_name ?? "--";
  const title = timeline?.title ?? chain?.source_id ?? incidentId;

  const requestedState = (() => {
    if (approvalId && requestedApproval) return t("states.pending");
    if (approvalId && timelineApprovalIds.includes(approvalId)) return t("states.timelineLinked");
    if (approvalId) return t("states.notPending");
    if (incidentPendingMatches.length > 0) return t("states.pending");
    if (linkedApprovalIds.length > 0) return t("states.notPendingLinked");
    return t("states.noApproval");
  })();

  const authorizationHref = `/authorizations?project_id=${encodedProjectId}&incident_id=${encodedIncidentId}${
    encodedApprovalId ? `&approval_id=${encodedApprovalId}` : ""
  }`;

  return (
    <section className="border border-[#e0ddd4] bg-white" aria-busy={loading}>
      <div className="flex flex-wrap items-start justify-between gap-3 border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
        <div className="flex min-w-0 items-start gap-3">
          <span className="flex h-9 w-9 shrink-0 items-center justify-center border border-[#9bb6d9] bg-[#eef5ff] text-[#1f5b9b]">
            <KeyRound className="h-4 w-4" aria-hidden="true" />
          </span>
          <div className="min-w-0">
            <h2 className="text-sm font-semibold text-[#141413]">{t("title")}</h2>
            <p className="mt-1 truncate font-mono text-xs text-[#77736a]">{incidentId}</p>
            <p className="mt-1 truncate text-xs text-[#5f5b52]" title={title}>{title}</p>
          </div>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          {loading ? (
            <span className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#5f5b52]">
              <RefreshCw className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />
              {t("loading")}
            </span>
          ) : null}
          <Link
            href={`/awooop/approvals?project_id=${encodedProjectId}&incident_id=${encodedIncidentId}` as never}
            className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2.5 py-1 text-xs font-semibold text-[#141413] hover:border-[#d97757]"
          >
            {t("openApprovals")}
            <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
          </Link>
          <Link
            href={`/awooop/work-items?project_id=${encodedProjectId}&incident_id=${encodedIncidentId}` as never}
            className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2.5 py-1 text-xs font-semibold text-[#141413] hover:border-[#d97757]"
          >
            {t("openWorkItems")}
            <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
          </Link>
          <Link
            href={`/awooop/runs?project_id=${encodedProjectId}&incident_id=${encodedIncidentId}` as never}
            className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2.5 py-1 text-xs font-semibold text-[#141413] hover:border-[#1f6feb]"
          >
            {t("openRuns")}
            <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
          </Link>
          <Link
            href={`/tickets?project_id=${encodedProjectId}&incident_id=${encodedIncidentId}` as never}
            className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2.5 py-1 text-xs font-semibold text-[#141413] hover:border-[#2f7d72]"
          >
            {t("openTickets")}
            <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
          </Link>
        </div>
      </div>

      {error ? (
        <div className="flex items-start gap-2 border-b border-[#ead9b4] bg-[#fff7e8] px-4 py-3 text-xs leading-5 text-[#8a5a08]">
          <TriangleAlert className="mt-0.5 h-4 w-4 shrink-0" aria-hidden="true" />
          {error}
        </div>
      ) : null}

      <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-5">
        {[
          [t("metrics.authorization"), requestedState],
          [t("metrics.pendingRows"), String(incidentPendingMatches.length)],
          [t("metrics.stage"), chain?.current_stage ?? "--"],
          [t("metrics.verification"), verifier?.status ?? chain?.verification ?? "--"],
          [t("metrics.handoff"), needsHuman ? t("needsHuman.yes") : t("needsHuman.no")],
        ].map(([label, value]) => (
          <div key={label} className="min-w-0 bg-white px-4 py-3">
            <p className="text-xs font-semibold text-[#77736a]">{label}</p>
            <p className="mt-2 truncate font-mono text-sm font-semibold text-[#141413]" title={String(value)}>
              {value}
            </p>
          </div>
        ))}
      </div>

      <AwoooPStatusChainPanel chain={chain} className="border-x-0 border-t-0" />

      <div className="grid gap-px bg-[#e0ddd4] lg:grid-cols-[1fr_1fr]">
        <div className="min-w-0 bg-white p-4">
          <div className="flex items-center gap-2">
            <SearchCheck className="h-4 w-4 text-brand-accent" aria-hidden="true" />
            <h3 className="text-sm font-semibold text-[#141413]">{t("authorizationTitle")}</h3>
          </div>
          <div className="mt-3 flex flex-wrap gap-2">
            {linkedApprovalIds.length > 0 ? linkedApprovalIds.slice(0, 6).map((id) => (
              <Link
                key={id}
                href={`/authorizations?project_id=${encodedProjectId}&incident_id=${encodedIncidentId}&approval_id=${encodeURIComponent(id)}` as never}
                className={cn(
                  "inline-flex max-w-full items-center gap-1.5 border px-2 py-1 font-mono text-[11px] font-semibold",
                  id === approvalId
                    ? "border-[#1f6feb] bg-[#eef5ff] text-[#1f5b9b]"
                    : "border-[#d8d3c7] bg-[#faf9f3] text-[#5f5b52]"
                )}
              >
                <span className="truncate">{id}</span>
              </Link>
            )) : (
              <span className="text-sm text-[#77736a]">{t("emptyApprovalIds")}</span>
            )}
          </div>
          {incidentPendingMatches.length > 0 ? (
            <div className="mt-3 grid gap-2">
              {incidentPendingMatches.slice(0, 3).map((approval) => (
                <div key={approval.id} className="min-w-0 border border-[#eee9dd] bg-white px-3 py-2">
                  <div className="flex items-center justify-between gap-2">
                    <span className="truncate font-mono text-xs font-semibold text-[#141413]">{approval.id}</span>
                    <span className={cn("shrink-0 border px-2 py-0.5 text-[11px] font-semibold", timelineStatusClass(approval.status))}>
                      {approval.status}
                    </span>
                  </div>
                  <p className="mt-1 truncate text-xs text-[#5f5b52]" title={approval.action}>{approval.action}</p>
                  <p className="mt-1 font-mono text-[11px] text-[#77736a]">
                    {t("signatures", {
                      current: approval.current_signatures,
                      required: approval.required_signatures,
                    })}
                  </p>
                </div>
              ))}
            </div>
          ) : (
            <p className="mt-3 text-xs leading-5 text-[#5f5b52]">
              {approvalId ? t("notPendingExplanation") : t("noPendingExplanation")}
            </p>
          )}
          <Link
            href={authorizationHref as never}
            className="mt-3 inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2.5 py-1 text-xs font-semibold text-[#141413] hover:border-[#1f6feb]"
          >
            {t("openFocusedAuthorization")}
            <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
          </Link>
        </div>

        <div className="min-w-0 bg-white p-4">
          <div className="flex items-center gap-2">
            <GitBranch className="h-4 w-4 text-brand-accent" aria-hidden="true" />
            <h3 className="text-sm font-semibold text-[#141413]">{t("flowTitle")}</h3>
          </div>
          {timeline?.ascii_timeline ? (
            <p className="mt-3 break-words border border-[#eee9dd] bg-[#faf9f3] px-3 py-2 font-mono text-xs leading-6 text-[#5f5b52]">
              {timeline.ascii_timeline}
            </p>
          ) : (
            <p className="mt-3 text-sm text-[#77736a]">
              {loading ? t("loading") : t("timelineEmpty")}
            </p>
          )}
          {stages.length > 0 ? (
            <div className="mt-3 grid gap-2 md:grid-cols-2">
              {stages.slice(0, 6).map((stage) => (
                <div key={stage.stage} className="min-w-0 border border-[#eee9dd] bg-white px-3 py-2">
                  <div className="flex items-center justify-between gap-2">
                    <span className="truncate text-xs font-semibold text-[#77736a]">{stage.label}</span>
                    <span className={cn("shrink-0 border px-2 py-0.5 text-[11px] font-semibold", timelineStatusClass(stage.status))}>
                      {stage.status}
                    </span>
                  </div>
                  <p className="mt-1 truncate text-xs font-semibold text-[#141413]" title={stage.title}>
                    {stage.title}
                  </p>
                </div>
              ))}
            </div>
          ) : null}
        </div>
      </div>

      <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-4">
        {[
          [t("evidence.nextAction"), outcome?.next_action ?? chain?.next_step ?? "--"],
          [t("evidence.reason"), outcome?.human_action_reason ?? "--"],
          [t("evidence.execution"), outcome?.execution_result?.summary_zh ?? executor?.title ?? "--"],
          [t("evidence.ansible"), ansible?.latest_playbook_path ?? ansible?.latest_catalog_id ?? "--"],
          [t("evidence.mcp"), t("evidence.mcpValue", {
            success: chain?.mcp?.gateway?.success ?? 0,
            total: chain?.mcp?.gateway?.total ?? 0,
            tool: topMcpTool,
          })],
          [t("evidence.km"), km?.title ?? String(chain?.evidence?.knowledge_entries ?? 0)],
          [t("evidence.notification"), (outcome?.notification?.channels ?? []).join(", ") || "--"],
          [t("evidence.events"), timeline ? String(timeline.events.length) : "--"],
        ].map(([label, value]) => (
          <div key={label} className="min-w-0 bg-white px-4 py-3">
            <p className="text-xs font-semibold text-[#77736a]">{label}</p>
            <p className="mt-2 truncate font-mono text-xs text-[#141413]" title={String(value)}>
              {value}
            </p>
          </div>
        ))}
      </div>

      <div className="flex items-start gap-2 border-t border-[#e0ddd4] bg-[#faf9f3] px-4 py-3 text-xs leading-5 text-[#5f5b52]">
        <ListChecks className="mt-0.5 h-4 w-4 shrink-0 text-brand-accent" aria-hidden="true" />
        <p>{t("boundary")}</p>
      </div>
    </section>
  );
}
