"use client";

import { AlertTriangle, Check, ShieldAlert, ShieldCheck } from "lucide-react";
import { cn } from "cn";

import type {
  PolicyVerdict,
  PolicyWarning,
} from "@/services/employee-requests/employee-requests.types";

/**
 * The travel-policy verdict: the headline, then one row per rule.
 *
 * One component for every surface that shows a verdict — step 4 of the request
 * overlay, the Request-submitted screen, and the Policy check panel on a
 * My-requests card. They can render the same thing because the API deliberately
 * returns the same `policy` shape from the preview and the submit; a second
 * renderer would be a second chance to disagree with the server about whether a
 * trip is in policy.
 *
 * Three things here come straight from the contract and are easy to get wrong:
 *
 *   - A rule that is switched off emits NO check at all. So this renders
 *     exactly the rows it is given and never fills in a missing rule as a tick.
 *   - `advisory: true` rows (today only passport validity) are shown but are
 *     excluded from `flagCount`. The headline therefore counts flags, not red
 *     rows, and those two legitimately differ — an advisory is marked as such
 *     rather than being dressed up as a failure.
 *   - Out of policy never blocks. The headline says so in as many words,
 *     because a red shield with no explanation reads like a refusal.
 */

export function PolicyChecks({
  policy,
  warnings = [],
  policyName,
  className,
}: {
  policy: PolicyVerdict;
  warnings?: PolicyWarning[];
  /** The matched policy's name, when a surface knows it. The employee-facing
   *  API does not return one today, so this is usually absent. */
  policyName?: { name: string; matchedBy?: string } | null;
  className?: string;
}) {
  const flags = policy.flagCount;
  const checks = policy.checks ?? [];

  return (
    <div className={className}>
      {/* `mb-[18px]`, not the 10px it had: the headline is a sentence ABOUT the
          list below it, and at 10px it read as the first row's own caption
          (LEIS-1046). The policy-name callout under it keeps the tighter gap —
          that one IS part of the list's framing. */}
      <p
        className={cn(
          "m-0 mb-[18px] flex items-center gap-2 text-[13px] font-semibold",
          flags > 0 ? "text-[var(--fra-rejected)]" : "text-[var(--fra-approved)]"
        )}
      >
        {flags > 0 ? (
          <ShieldAlert aria-hidden className="size-4 shrink-0" />
        ) : (
          <ShieldCheck aria-hidden className="size-4 shrink-0" />
        )}
        {flags > 0
          ? `${flags} item${flags > 1 ? "s" : ""} outside policy. You can still submit with a business reason.`
          : "Within travel policy"}
      </p>

      {policyName && (
        <p className="m-0 mb-2.5 flex flex-wrap items-center gap-x-2 gap-y-1 rounded-[10px] bg-[var(--fra-blue-bg)] px-[12px] py-2.5 text-[13px] text-[var(--fra-text)]">
          <span>
            Policy: <strong className="text-[var(--fra-heading)]">{policyName.name}</strong>
          </span>
          {policyName.matchedBy && (
            <small className="basis-full text-xs text-[var(--fra-muted)]">
              {policyName.matchedBy}
            </small>
          )}
        </p>
      )}

      {checks.length > 0 && (
        <ul className="m-0 grid list-none gap-2 p-0">
          {checks.map((check) => {
            // An advisory that fails is a heads-up, not a breach — it is not in
            // flagCount, so colouring it like one would make the headline look
            // wrong by exactly that many rows.
            const failed = !check.ok && !check.advisory;
            const advisory = !check.ok && check.advisory;
            return (
              <li
                key={check.rule}
                className={cn(
                  "flex items-start gap-[12px] rounded-xl border px-3.5 py-[12px] text-sm",
                  failed
                    ? "border-transparent bg-[var(--fra-rejected-bg)]"
                    : advisory
                      ? "border-transparent bg-[var(--fra-pending-bg)]"
                      : "border-[var(--fra-border)] bg-[var(--fra-surface)]"
                )}
              >
                <span
                  aria-hidden
                  className={cn(
                    "inline-flex size-7 shrink-0 items-center justify-center rounded-lg",
                    failed
                      ? "bg-[var(--fra-rejected-solid)] text-white"
                      : advisory
                        ? "bg-[var(--fra-pending)] text-white"
                        : "bg-[var(--fra-approved-bg)] text-[var(--fra-approved)]"
                  )}
                >
                  {check.ok ? <Check className="size-4" /> : <AlertTriangle className="size-4" />}
                </span>
                <div className="min-w-0">
                  <strong className="block font-semibold text-[var(--fra-text)]">
                    {check.label}
                    {/* Carries the pass/fail to assistive tech, which cannot
                        read the icon's colour. */}
                    <span className="sr-only">
                      {check.ok ? " — passed" : advisory ? " — advisory" : " — outside policy"}
                    </span>
                  </strong>
                  <small className="mt-0.5 block text-[13px] text-[var(--fra-muted)]">
                    {check.detail}
                  </small>
                </div>
              </li>
            );
          })}
        </ul>
      )}

      {warnings.length > 0 && (
        <ul className="m-0 mt-2 grid list-none gap-2 p-0">
          {warnings.map((w) => (
            <li
              key={w.code}
              className="flex items-start gap-2.5 rounded-xl bg-[var(--fra-pending-bg)] px-3.5 py-[12px] text-[13px] text-[var(--fra-text)]"
            >
              <AlertTriangle
                aria-hidden
                className="mt-0.5 size-4 shrink-0 text-[var(--fra-pending)]"
              />
              <span>{w.message}</span>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

/** Skeleton for while the preview is in flight. Matches the row height so the
 *  overlay does not jump when the real verdict lands. */
export function PolicyChecksSkeleton({ rows = 3 }: { rows?: number }) {
  return (
    <div aria-hidden>
      <div className="mb-[18px] h-4 w-64 max-w-full animate-pulse rounded bg-[var(--fra-hover)]" />
      <div className="grid gap-2">
        {Array.from({ length: rows }).map((_, i) => (
          <div
            key={i}
            className="h-[62px] animate-pulse rounded-xl border border-[var(--fra-border)] bg-[var(--fra-surface-2)] motion-reduce:animate-none"
          />
        ))}
      </div>
    </div>
  );
}
