"use client";

import { useQuery } from "@tanstack/react-query";
import Link from "next/link";

import {
  listCompanyRequests,
  type AdminRequestRow,
} from "@/services/admin-approvals/admin-approvals.client";
import {
  displayName,
  formatMoney,
  formatShortDate,
  initials,
  timeAgo,
} from "@/components/admin-approvals/format";
import { HomeEmpty, HomeError, HomeSection, HomeSkeleton } from "./HomeSection";

const SHOWN = 3;

/**
 * "Waiting for your approval" — D0 (LEIS-1019).
 *
 * ── Oldest first, not newest ────────────────────────────────────────────
 *
 * The queue page defaults to newest-first because an admin working through it
 * wants to see what just arrived. This section is the opposite question — what
 * has been waiting longest — so it sorts ascending. A request that has sat for
 * three days is the one that should be on the landing page, not the one
 * submitted five minutes ago.
 *
 * ── Why Review links to the queue instead of opening the overlay ────────
 *
 * `ReviewOverlay` is a plain conditional modal and would render here, but two
 * things argue against it: it fills half its panels from
 * `components/admin-approvals/sample.ts` because `GET /business/requests/:id`
 * was never implemented, and it fires a reprice on mount. Duplicating both
 * onto a second page doubles the surface of a known gap. The queue opens the
 * same overlay from `?request=`, and lands the admin somewhere they can act on
 * the rest of the list too.
 */
export function AwaitingApproval({ token }: { token: string }) {
  const { data, isPending, isError, refetch } = useQuery({
    queryKey: ["admin-requests", "pending-oldest"],
    queryFn: async () => {
      const res = await listCompanyRequests(token, {
        status: "PENDING",
        type: "all",
        outOfPolicy: false,
        search: "",
        sortBy: "submitted",
        sortOrder: "asc",
        page: 1,
        limit: SHOWN,
      });
      if (!res.success) throw new Error(res.message ?? "Could not load the approval queue.");
      return res;
    },
    enabled: Boolean(token),
    refetchOnWindowFocus: false,
    staleTime: 30_000,
    refetchInterval: 30_000,
    // See useMyRequests' identical note: a periodic background poll with
    // nothing time-sensitive on it, so there's no cost to more retry
    // headroom against a transient failure (a slow backend restart, a brief
    // network hiccup) than React Query's own default (3) gives it.
    retry: 5,
  });

  const rows = (data?.data ?? []) as AdminRequestRow[];
  const total =
    (data?.meta as { counts?: { byStatus?: Record<string, number> } } | undefined)?.counts?.byStatus
      ?.PENDING ?? rows.length;

  return (
    <HomeSection
      title="Waiting for your approval"
      viewAll={{ href: "/admin/flight-approvals?status=PENDING", label: "Open approval queue" }}
    >
      <div aria-live="polite" aria-busy={isPending}>
        {isPending && (
          <>
            <span className="sr-only">Loading requests waiting for approval…</span>
            <HomeSkeleton rows={3} height={84} />
          </>
        )}

        {!isPending && isError && (
          <HomeError what="the approval queue" onRetry={() => void refetch()} />
        )}

        {!isPending && !isError && rows.length === 0 && (
          <HomeEmpty title="You're all caught up." body="Nothing is waiting for your approval." />
        )}

        {!isPending && !isError && rows.length > 0 && (
          <div className="grid gap-[12px]">
            {rows.map((row) => (
              <PendingRow key={row.id} row={row} />
            ))}
            {total > rows.length && (
              <p className="m-0 text-[13px]" style={{ color: "var(--fra-muted)" }}>
                Showing the {rows.length} longest waiting of {total} pending requests.
              </p>
            )}
          </div>
        )}
      </div>
    </HomeSection>
  );
}

function PendingRow({ row }: { row: AdminRequestRow }) {
  const name = displayName(row.employee.name) ?? row.employee.workEmail;
  const where = row.flight
    ? `${row.flight.origin} → ${row.flight.destination}`
    : row.hotel
      ? `${row.hotel.property}, ${row.hotel.location}`
      : "—";
  // Nullable, and a null here already white-screened the admin queue once
  // (commit 37fa392). Never format it without the guard.
  const when = row.travelStartDate ? formatShortDate(row.travelStartDate) : "Dates TBC";
  const isCancellation = row.kind === "CANCELLATION";
  const isChange = row.kind === "CHANGE";

  return (
    <div
      className="flex flex-wrap items-center gap-[12px] rounded-[14px] p-[16px]"
      style={{
        backgroundColor: "var(--fra-surface)",
        border: "1px solid var(--fra-border)",
        boxShadow: "var(--fra-shadow)",
      }}
    >
      <span
        aria-hidden="true"
        className="inline-flex size-[38px] shrink-0 items-center justify-center rounded-full text-[13px] font-bold"
        style={{ backgroundColor: "var(--fra-blue-bg)", color: "var(--fra-navy)" }}
      >
        {initials(row.employee.name)}
      </span>

      <div className="min-w-0 flex-1">
        <p className="m-0 text-[11px] tracking-wide uppercase" style={{ color: "var(--fra-muted)" }}>
          {row.reference} · submitted {timeAgo(row.submittedAt)}
        </p>
        <p className="m-0 text-[15px] font-semibold" style={{ color: "var(--fra-heading)" }}>
          {name} · {where}
        </p>
        <p className="m-0 text-[13px]" style={{ color: "var(--fra-muted)" }}>
          {when} · Est. {formatMoney(row.cost.estTotal, row.cost.currency)}
        </p>
      </div>

      <div className="flex flex-wrap items-center gap-[6px]">
        {row.priority === "URGENT" && <Tag tone="rejected">Urgent</Tag>}
        {isCancellation && <Tag tone="info">Cancellation</Tag>}
        {isChange && <Tag tone="info">Change</Tag>}
        {row.policy.flagCount > 0 ? (
          <Tag tone="pending">
            {row.policy.flagCount} flag{row.policy.flagCount === 1 ? "" : "s"}
          </Tag>
        ) : (
          <Tag tone="approved">In policy</Tag>
        )}
        <Link
          href={`/admin/flight-approvals?request=${encodeURIComponent(row.reference)}`}
          className="inline-flex min-h-[40px] items-center rounded-[10px] px-[16px] text-[14px] font-semibold text-white no-underline"
          style={{ backgroundColor: "var(--fra-navy)" }}
        >
          Review
        </Link>
      </div>
    </div>
  );
}

const TONES = {
  pending: ["var(--fra-pending-bg)", "var(--fra-pending)"],
  approved: ["var(--fra-approved-bg)", "var(--fra-approved)"],
  rejected: ["var(--fra-rejected-bg)", "var(--fra-rejected)"],
  info: ["var(--fra-info-bg)", "var(--fra-info)"],
} as const;

function Tag({ tone, children }: { tone: keyof typeof TONES; children: React.ReactNode }) {
  const [bg, fg] = TONES[tone];
  return (
    <span
      className="inline-flex items-center rounded-full px-[10px] py-[5px] text-[12px] font-semibold"
      style={{ backgroundColor: bg, color: fg }}
    >
      {children}
    </span>
  );
}
