"use client";

import { useRouter } from "next/navigation";
import Link from "next/link";
import { Eye, Hotel, Plane, UserRound } from "lucide-react";

import { FraBadge } from "@/components/employee-requests/fra-primitives";
import { BookedTripActions } from "@/components/employee-requests/BookedTripActions";
import { SupportBadge } from "@/components/employee-requests/SupportBadge";
import { formatDate, formatMoney, tripDays } from "@/services/employee-requests/format";
import {
  STATUS_LABEL,
  STATUS_TONE,
  statusLineFor,
} from "@/services/employee-requests/request-status";
import type { MyRequestRow } from "@/services/employee-requests/employee-requests.types";

/**
 * A request, as the home page shows it (LEIS-1016).
 *
 * ── Why this is not `RequestCard` with a prop ───────────────────────────
 *
 * It started as one. The two cards now differ in what they ARE, not in how
 * much of the same thing they show: this one has no status tracker, no
 * details toggle, no inline reply form, and the whole surface is a link to
 * somewhere else. Four `variant === "compact"` branches threaded through 590
 * lines would leave both behaviours harder to read than either is apart.
 *
 * What they must not differ on is vocabulary, so the status label, its tone
 * and the one-line summary all come from
 * `services/employee-requests/request-status.ts`, which `RequestCard` reads
 * too. A request called "Not approved" here is called that there.
 *
 * ── Why the card links instead of expanding ─────────────────────────────
 *
 * This is a landing page. Expanding a request in place pushes the travel
 * policy and the passport card below the fold, and the full detail — the
 * tracker, the admin's question, the fare history — already exists one click
 * away on My requests. So the card is a summary that hands over.
 *
 * ── The click target ────────────────────────────────────────────────────
 *
 * The heading is a real `<Link>`, and the card repeats that navigation on
 * click. Not an `<a>` wrapped around everything: the card contains buttons,
 * and a link containing a button is invalid markup that browsers and screen
 * readers disagree about. This way the keyboard path is the heading link —
 * one tab stop, correctly announced — and the mouse path is the whole card.
 */
export function HomeRequestCard({ row }: { row: MyRequestRow }) {
  const router = useRouter();
  const href = `/employee-requests?id=${encodeURIComponent(row.reference)}`;

  const flight = row.trip.flight;
  const hotel = row.trip.hotel as { property?: string; location?: string } | null;
  const isHotel = row.type === "HOTEL";
  const days = tripDays(row.trip.travelStartDate, row.trip.travelEndDate);
  const line = statusLineFor(row);

  const where = isHotel
    ? [hotel?.property, hotel?.location].filter(Boolean).join(", ") || "—"
    : flight
      ? `${flight.origin} → ${flight.destination}`
      : "—";

  return (
    <article
      id={`home-request-${row.reference}`}
      onClick={() => router.push(href)}
      className="cursor-pointer rounded-2xl border p-[20px] transition-shadow hover:shadow-[var(--fra-shadow-lg)]"
      style={{
        backgroundColor: "var(--fra-surface)",
        /*
         * The status stripe `RequestCard` carries, kept — it is what makes a
         * column of these skimmable for the one needing attention.
         *
         * Drawn as an INSET shadow, not `border-left`. These routes load the
         * vendored Bootstrap, which sets the border with `!important`, and an
         * `!important` declaration beats an inline style — measured: the left
         * edge came out 1px of Bootstrap's #dee2e6 rather than 4px of the
         * status colour. `box-shadow` carries no such rule, so it lands.
         */
        boxShadow: `inset 4px 0 0 0 ${STRIPE[row.status] ?? "var(--fra-pending)"}, var(--fra-shadow)`,
      }}
    >
      <div className="mb-[12px] flex flex-wrap items-center gap-[10px]">
        <h3 className="m-0 text-[17px] font-bold" style={{ color: "var(--fra-heading)" }}>
          <Link
            href={href}
            // The card's own handler would fire too and push twice.
            onClick={(e) => e.stopPropagation()}
            className="no-underline hover:underline"
            style={{ color: "inherit" }}
          >
            {isHotel ? "Hotel" : "Flight"} request #{row.reference}
          </Link>
        </h3>
        {row.supportStatus !== "WITH_SUPPORT" && <FraBadge tone={STATUS_TONE[row.status]}>{STATUS_LABEL[row.status]}</FraBadge>}
        <SupportBadge status={row.supportStatus} reference={row.supportReference} />
        {row.priority === "URGENT" && <FraBadge tone="pending">Urgent</FraBadge>}
      </div>

      {/* Only when the reader is not simply the person who asked. */}
      {row.viewerRole !== "BOTH" && (
        <p
          className="m-0 mb-[12px] flex flex-wrap items-center gap-x-[8px] gap-y-[2px] text-[13px]"
          style={{ color: "var(--fra-muted)" }}
        >
          <UserRound aria-hidden="true" className="size-[14px] shrink-0" />
          {row.viewerRole === "REQUESTER" ? (
            <span>
              For{" "}
              <strong className="font-semibold" style={{ color: "var(--fra-heading)" }}>
                {row.traveller.name ?? row.traveller.workEmail}
              </strong>{" "}
              · you requested it
            </span>
          ) : (
            <>
              <span>
                Booked by{" "}
                <strong className="font-semibold" style={{ color: "var(--fra-heading)" }}>
                  {row.requester.name ?? row.requester.workEmail}
                </strong>
              </span>
              <span className="inline-flex items-center gap-[4px]">
                <Eye aria-hidden="true" className="size-[14px]" /> view only
              </span>
            </>
          )}
        </p>
      )}

      <div
        className="grid grid-cols-1 gap-[16px] rounded-xl p-[16px] sm:grid-cols-2 lg:grid-cols-4"
        style={{ backgroundColor: "var(--fra-surface-2)" }}
      >
        <div className="flex items-start gap-[12px]">
          <span
            aria-hidden="true"
            className="inline-flex size-10 shrink-0 items-center justify-center rounded-xl text-white"
            style={{ backgroundColor: "var(--fra-navy)" }}
          >
            {isHotel ? <Hotel className="size-5" /> : <Plane className="size-5" />}
          </span>
          <div className="min-w-0">
            <small className="block text-xs" style={{ color: "var(--fra-muted)" }}>
              Trip details
            </small>
            <strong
              className="block text-sm font-semibold"
              style={{ color: "var(--fra-heading)" }}
            >
              {where}
            </strong>
            <span className="block text-xs" style={{ color: "var(--fra-muted)" }}>
              {formatDate(row.trip.travelStartDate)}
              {row.trip.travelEndDate && row.trip.travelEndDate !== row.trip.travelStartDate
                ? ` – ${formatDate(row.trip.travelEndDate)}${days ? ` (${days} day${days === 1 ? "" : "s"})` : ""}`
                : ""}
            </span>
          </div>
        </div>
        <Cell label="Client" value={row.business.client || "—"} />
        <Cell label="Purpose" value={row.business.meetingType || "—"} />
        <Cell label="Est. cost" value={formatMoney(row.cost.estTotal, row.cost.currency)} emphasis />
      </div>

      {/*
       * One line instead of the full panel My requests shows. The admin's
       * question, the reply box and the fare history all live on that page;
       * repeating them here turns a landing page into a second inbox.
       */}
      {line && (
        <p
          className="mt-[12px] mb-0 rounded-[10px] px-[12px] py-[10px] text-[13px]"
          style={{ backgroundColor: LINE_BG[line.tone], color: LINE_FG[line.tone] }}
        >
          {line.text}
        </p>
      )}

      {/* Actions act on THIS request; they must not also navigate. */}
      <div onClick={(e) => e.stopPropagation()}>
        <BookedTripActions row={row} />
      </div>
    </article>
  );
}

const STRIPE: Partial<Record<MyRequestRow["status"], string>> = {
  INFO_REQUESTED: "var(--fra-info-solid)",
  REJECTED: "var(--fra-rejected-solid)",
  BOOKING_FAILED: "var(--fra-rejected-solid)",
  // LEIS-1044: the travel date passed before anyone decided it.
  EXPIRED: "var(--fra-rejected-solid)",
  APPROVED: "var(--fra-approved-solid)",
  BOOKED: "var(--fra-approved-solid)",
};

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

const LINE_FG = {
  pending: "var(--fra-pending)",
  approved: "var(--fra-approved)",
  rejected: "var(--fra-rejected)",
  info: "var(--fra-info)",
} as const;

function Cell({ label, value, emphasis }: { label: string; value: string; emphasis?: boolean }) {
  return (
    <div className="min-w-0">
      <small className="block text-xs" style={{ color: "var(--fra-muted)" }}>
        {label}
      </small>
      <strong
        className={`block ${emphasis ? "text-base" : "text-sm"} font-semibold`}
        style={{ color: "var(--fra-heading)" }}
      >
        {value}
      </strong>
    </div>
  );
}
