"use client";

import Link from "next/link";

import { HomeRequestCard } from "./HomeRequestCard";
import { useMyRequests } from "@/services/employee-requests/useMyRequests";
import { fraButton } from "@/components/employee-requests/fra-primitives";
import { HomeEmpty, HomeError, HomeSection, HomeSkeleton } from "./HomeSection";

/** The ticket's proposed cap. Three fills the column without pushing the
 *  policy panel beside it off the first screen. */
const SHOWN = 3;

/**
 * "Your recent requests" — E0 (LEIS-1016).
 *
 * ── Why a card of its own ───────────────────────────────────────────────
 *
 * This first reused `RequestCard`, which was right while the two showed the
 * same thing. They no longer do: the home card has no tracker, no details
 * toggle and no inline reply, and the whole surface links to My requests
 * instead. See `HomeRequestCard` for the reasoning and for what the two still
 * share — the status vocabulary, which lives in one module so a request is
 * not called two different things on two pages.
 *
 * ── Why the newest three, unfiltered ────────────────────────────────────
 *
 * Not "the three that need attention": a page that hides a request once it is
 * approved makes an employee wonder where it went. The full list with its
 * Open/Closed tabs is one link away.
 */
export function RecentRequests() {
  const { data, isPending, isError, refetch } = useMyRequests();

  const all = data?.data ?? [];
  const rows = all.slice(0, SHOWN);
  const total = data?.meta?.total ?? all.length;

  return (
    <HomeSection
      title="Your recent requests"
      viewAll={
        all.length > 0 ? { href: "/employee-requests", label: "View all requests" } : undefined
      }
    >
      <div aria-live="polite" aria-busy={isPending}>
        {isPending && (
          <>
            <span className="sr-only">Loading your requests…</span>
            <HomeSkeleton rows={2} height={180} />
          </>
        )}

        {!isPending && isError && <HomeError what="your requests" onRetry={() => void refetch()} />}

        {!isPending && !isError && rows.length === 0 && (
          <HomeEmpty
            title="No requests yet"
            body="Search above to plan your first trip."
            action={
              <Link href="/srp/flights" className={fraButton.primary}>
                Find a flight
              </Link>
            }
          />
        )}

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