"use client";

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

import { getCompanySummary } from "@/services/admin-approvals/admin-approvals.client";
import { fetchOverview } from "@/services/travel-policy/travel-policy.client";
import { listEmployees, listInvited } from "@/services/workforce/workforce.client";
import { listCards } from "@/services/payment-cards/payment-cards.client";
import { BRAND_LABEL, type CardBrand } from "@/services/payment-cards/card-utils";
import { formatWholeMoney } from "@/components/admin-approvals/format";
import { BzStat } from "@/components/ui/BzStat";
import { HomeCard, HomeError, HomeSection, HomeSkeleton } from "./HomeSection";

import "./home-panels.css";

const QUEUE = "/admin/flight-approvals";

/**
 * "Company at a glance" and the quick links — D0 (LEIS-1021).
 *
 * ── The four figures come from the queue's own summary ──────────────────
 *
 * `GET /admin/requests/summary` is what the approval queue's dashboard cards
 * read, and the ticket requires these to agree with it. So they are the same
 * call rather than a second computation — including `outOfPolicy`, which the
 * API defines as flagged AND still pending. The ticket's prose says "requests
 * and bookings with flags, this month", which would be a different number and
 * would then disagree with the chip this card links to.
 *
 * ── Why three separate quick-link calls ─────────────────────────────────
 *
 * There is no counts endpoint for any of them. Workforce derives its totals
 * client-side on its own page too, and the default card is `listCards().find(
 * isDefault)` because no "default card" route exists. Each is independent, so
 * one failing leaves the other two rendered rather than blanking the row.
 */
export function CompanyGlance({ token }: { token: string }) {
  const summary = useQuery({
    queryKey: ["admin-summary", "home"],
    queryFn: async () => {
      const res = await getCompanySummary(token);
      if (!res.success) throw new Error(res.message ?? "Could not load your company summary.");
      return res.data!;
    },
    enabled: Boolean(token),
    refetchOnWindowFocus: false,
    staleTime: 60_000,
  });

  return (
    <>
      <HomeSection title="Company at a glance" className="home-glance">
        <div aria-live="polite" aria-busy={summary.isPending}>
          {summary.isPending && (
            <>
              <span className="sr-only">Loading your company figures…</span>
              <HomeSkeleton rows={2} height={84} />
            </>
          )}
          {!summary.isPending && summary.isError && (
            <HomeError what="your company figures" onRetry={() => void summary.refetch()} />
          )}
          {!summary.isPending && !summary.isError && summary.data && (
            <div className="bz-stats">
              <BzStat
                tone="amber"
                icon="bi-hourglass-split"
                label="Awaiting approval"
                value={String(summary.data.awaitingApproval.count)}
                sub={
                  summary.data.awaitingApproval.urgent
                    ? `${summary.data.awaitingApproval.urgent} marked urgent`
                    : "Nothing urgent"
                }
                href={`${QUEUE}?status=PENDING`}
              />
              <BzStat
                tone="coral"
                icon="bi-flag"
                label="Out of policy"
                value={String(summary.data.outOfPolicy.count)}
                sub="Flagged and still pending"
                href={`${QUEUE}?outOfPolicy=true`}
              />
              <BzStat
                tone="green"
                icon="bi-credit-card"
                label="Spend this month"
                value={formatWholeMoney(summary.data.spend.thisMonth, summary.data.spend.currency)}
                sub={`Last month ${formatWholeMoney(summary.data.spend.lastMonth, summary.data.spend.currency)}`}
              />
              <BzStat
                tone="indigo"
                icon="bi-clock-history"
                label="Pending spend"
                value={formatWholeMoney(summary.data.spend.pending, summary.data.spend.currency)}
                sub="Estimated, not yet charged"
                href={`${QUEUE}?status=PENDING`}
              />
            </div>
          )}
        </div>
      </HomeSection>

      <QuickLinks token={token} />
    </>
  );
}

function QuickLinks({ token }: { token: string }) {
  const policy = useQuery({
    queryKey: ["home-quicklinks", "policy"],
    queryFn: async () => {
      const res = await fetchOverview(token);
      if (!res.success) throw new Error("policy");
      return res.data!;
    },
    enabled: Boolean(token),
    refetchOnWindowFocus: false,
    staleTime: 5 * 60_000,
    retry: false,
  });

  const workforce = useQuery({
    queryKey: ["home-quicklinks", "workforce"],
    queryFn: async () => {
      const [active, invited] = await Promise.all([
        listEmployees(token, { status: "ACTIVE", limit: 1 }),
        listInvited(token),
      ]);
      const total = (active.meta as { total?: number } | undefined)?.total ?? 0;
      const pending = (invited.data ?? []).filter((row) => !row.expired).length;
      return { active: total, invited: pending };
    },
    enabled: Boolean(token),
    refetchOnWindowFocus: false,
    staleTime: 5 * 60_000,
    retry: false,
  });

  const cards = useQuery({
    queryKey: ["home-quicklinks", "cards"],
    queryFn: async () => {
      const res = await listCards(token);
      if (!res.success) throw new Error("cards");
      return res.data?.cards.find((card) => card.isDefault) ?? null;
    },
    enabled: Boolean(token),
    refetchOnWindowFocus: false,
    staleTime: 5 * 60_000,
    retry: false,
  });

  const defaultCard = cards.data;

  return (
    <HomeSection title="Quick links" className="mt-[24px]">
      <HomeCard className="grid gap-[2px] p-0">
        <QuickLink
          href="/admin/travel-policy"
          icon="bi-journal-check"
          label="Travel policy"
          value={policy.data ? `${policy.data.stats.groupCount} groups` : "—"}
        />
        <QuickLink
          href="/admin/workforce"
          icon="bi-people"
          label="Workforce"
          value={
            workforce.data
              ? `${workforce.data.active} active · ${workforce.data.invited} invited`
              : "—"
          }
        />
        <QuickLink
          href="/admin/payment-methods"
          icon="bi-credit-card"
          label="Payment methods"
          value={
            cards.isPending
              ? "—"
              : defaultCard
                ? `${BRAND_LABEL[defaultCard.brand as CardBrand] ?? defaultCard.brand} •••• ${defaultCard.last4}`
                : "No card added"
          }
        />
      </HomeCard>
    </HomeSection>
  );
}

function QuickLink({
  href,
  icon,
  label,
  value,
}: {
  href: string;
  icon: string;
  label: string;
  value: string;
}) {
  return (
    <Link
      href={href}
      className="flex items-center gap-[12px] px-[20px] py-[16px] no-underline"
      style={{ color: "var(--fra-text)" }}
    >
      <i className={`bi ${icon}`} aria-hidden="true" style={{ color: "var(--fra-navy-2)" }} />
      <span className="flex-1 text-[15px] font-semibold" style={{ color: "var(--fra-heading)" }}>
        {label}
      </span>
      <span className="text-[14px]" style={{ color: "var(--fra-muted)" }}>
        {value}
      </span>
    </Link>
  );
}
