"use client";

import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";

import { toast } from "@/lib/toast";
import { adminCancelRequest } from "@/services/admin-approvals/admin-approvals.client";
import { useMyRequests } from "@/services/employee-requests/useMyRequests";
import { useCancelOptions } from "@/services/employee-requests/useCancelOptions";
import { BookedTripActions } from "@/components/employee-requests/BookedTripActions";
import { SupportBadge } from "@/components/employee-requests/SupportBadge";
import { formatDate, formatMoney } from "@/services/employee-requests/format";
import type { MyRequestRow } from "@/services/employee-requests/employee-requests.types";
import { HomeEmpty, HomeError, HomeSection, HomeSkeleton } from "./HomeSection";

const SHOWN = 3;

/**
 * "Your recent bookings" — D0 (LEIS-1020).
 *
 * ── Why this uses the EMPLOYEE endpoint ─────────────────────────────────
 *
 * The section is the admin's OWN bookings, and there is no `booked_by_admin`
 * column to filter the company queue by — nor a requester filter on
 * `GET /admin/requests`, whose querystring is `additionalProperties: false`.
 *
 * But an admin is a business user like any other, and `GET /business/requests`
 * is `requireBusinessAuth`, scoped to the caller. `POST /checkout/direct`
 * creates the trip already BOOKED with `requesterId` = whoever paid. So the
 * admin's own bookings are simply their own requests with status BOOKED — no
 * new endpoint, no schema change, and it stays correct if an admin ever books
 * through the approval path instead.
 *
 * ── Change and Cancel ───────────────────────────────────────────────────
 *
 * Both are live as of LEIS-1013. Cancel is the ADMIN route
 * (`POST /admin/requests/:id/cancel`) rather than the employee's cancellation
 * request: an admin cancelling their own booking has nobody to ask, so the
 * trip goes straight to CANCELLED instead of raising a linked request for
 * somebody to approve. PRD §8.6 — the same reasoning that lets them book
 * directly in the first place.
 *
 * Change stays a linked request even for the admin, because changing a trip
 * means choosing a different flight, and that is the search and the request
 * overlay rather than a decision. Until that flow accepts an existing request
 * id, the button says so.
 */
export function RecentBookings({ token }: { token: string }) {
  const { data, isPending, isError, refetch } = useMyRequests();

  const booked = (data?.data ?? []).filter((row) => row.status === "BOOKED");
  const rows = booked.slice(0, SHOWN);

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

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

        {!isPending && !isError && rows.length === 0 && (
          <HomeEmpty
            title="No bookings yet"
            body="Use the search above to book for yourself or an employee."
          />
        )}

        {!isPending && !isError && rows.length > 0 && (
          <div className="grid gap-[12px]">
            {rows.map((row) => (
              <BookingRow key={row.id} row={row} token={token} />
            ))}
          </div>
        )}
      </div>
    </HomeSection>
  );
}

function BookingRow({ row, token }: { row: MyRequestRow; token: string }) {
  const queryClient = useQueryClient();
  const [confirming, setConfirming] = useState(false);
  const [reason, setReason] = useState("");
  const [busy, setBusy] = useState(false);
  // LEIS-1049: with the new flow on, an admin booking gets the same actions as any booked trip (instant cancel
  // inside the free window, a support request outside it). The admin's direct cancel and the "coming soon"
  // Change stub below are the flow-off behaviour and stay as they were until then.
  const options = useCancelOptions(row.id, row.canAct).data;
  const newFlow = Boolean(options?.flowEnabled && options.viewer.isRequester);

  const cancel = async () => {
    const trimmed = reason.trim();
    if (!trimmed) return;
    setBusy(true);
    const res = await adminCancelRequest(token, row.id, trimmed);
    setBusy(false);
    if (!res.success) {
      toast.error(res.message ?? "That booking could not be cancelled.");
      return;
    }
    toast.success(`${row.reference} cancelled.`);
    setConfirming(false);
    setReason("");
    await queryClient.invalidateQueries({ queryKey: ["employee-requests", "mine"] });
  };

  const flight = row.trip.flight;
  const where = flight ? `${flight.origin} → ${flight.destination}` : "—";
  const forWhom = row.viewerRole === "BOTH" ? "For yourself" : `For ${row.traveller.name ?? row.traveller.workEmail}`;

  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)",
      }}
    >
      <div className="min-w-0 flex-1">
        <p className="m-0 text-[11px] tracking-wide uppercase" style={{ color: "var(--fra-muted)" }}>
          {row.reference} · {row.type === "FLIGHT" ? "Flight" : "Hotel"} · Admin booking
        </p>
        <p className="m-0 text-[15px] font-semibold" style={{ color: "var(--fra-heading)" }}>
          {where}
        </p>
        <p className="m-0 text-[13px]" style={{ color: "var(--fra-muted)" }}>
          {formatDate(row.trip.travelStartDate)} · {forWhom} ·{" "}
          {formatMoney(row.cost.estTotal, row.cost.currency)}
          {row.policy.flagCount > 0 &&
            ` · ${row.policy.flagCount} flag${row.policy.flagCount === 1 ? "" : "s"}`}
        </p>
      </div>

      <div className="flex items-center gap-[8px]">
        {row.supportStatus !== "WITH_SUPPORT" && (
          <span
            className="inline-flex items-center rounded-full px-[10px] py-[5px] text-[12px] font-semibold"
            style={{ backgroundColor: "var(--fra-approved-bg)", color: "var(--fra-approved)" }}
          >
            Ticket issued
          </span>
        )}
        <SupportBadge status={row.supportStatus} reference={row.supportReference} />
        {!newFlow && (
          <>
            <button
              type="button"
              onClick={() =>
                toast.info("Changing a trip is coming soon. Cancel and book again for now.")
              }
              className="inline-flex min-h-[40px] items-center rounded-[10px] px-[14px] text-[14px] font-semibold"
              style={{ border: "1px solid var(--fra-border-strong)", color: "var(--fra-navy-2)" }}
            >
              Change
            </button>
            <button
              type="button"
              onClick={() => setConfirming((open) => !open)}
              aria-expanded={confirming}
              className="inline-flex min-h-[40px] items-center rounded-[10px] px-[14px] text-[14px] font-semibold"
              style={{
                border: "1px solid var(--fra-rejected-solid)",
                color: "var(--fra-rejected-solid)",
              }}
            >
              Cancel
            </button>
          </>
        )}
      </div>
      {newFlow && (
        <div className="basis-full">
          <BookedTripActions row={row} />
        </div>
      )}

      {/* Confirms in place rather than in a dialog: the row stays visible while
          the reason is typed, and there is no modal to stack. Cancelling a
          ticketed trip is irreversible, so the reason is required — it is what
          the employee sees on their own copy of the request. */}
      {!newFlow && confirming && (
        <form
          className="mt-[12px] w-full rounded-[10px] p-[12px]"
          style={{
            backgroundColor: "var(--fra-surface-2)",
            border: "1px solid var(--fra-border)",
          }}
          onSubmit={(e) => {
            e.preventDefault();
            void cancel();
          }}
        >
          <label
            htmlFor={`cancel-${row.id}`}
            className="mb-[8px] block text-[13px]"
            style={{ color: "var(--fra-text)" }}
          >
            This cancels {row.reference} outright — the traveller is told, and it cannot be
            undone. Why is it being cancelled?
          </label>
          <textarea
            id={`cancel-${row.id}`}
            value={reason}
            onChange={(e) => setReason(e.target.value)}
            rows={2}
            maxLength={5000}
            autoFocus
            disabled={busy}
            className="w-full resize-y rounded-[10px] px-[12px] py-[10px] text-[14px]"
            style={{
              border: "1px solid var(--fra-border-strong)",
              backgroundColor: "var(--fra-surface)",
              color: "var(--fra-text)",
            }}
          />
          <div className="mt-[10px] flex flex-wrap gap-[8px]">
            <button
              type="submit"
              disabled={busy || !reason.trim()}
              className="inline-flex min-h-[40px] items-center rounded-[10px] px-[14px] text-[14px] font-semibold text-white disabled:cursor-not-allowed disabled:opacity-50"
              style={{ backgroundColor: "var(--fra-rejected-solid)" }}
            >
              {busy ? "Cancelling…" : "Cancel this trip"}
            </button>
            <button
              type="button"
              onClick={() => setConfirming(false)}
              disabled={busy}
              className="inline-flex min-h-[40px] items-center rounded-[10px] px-[14px] text-[14px] font-semibold"
              style={{ border: "1px solid var(--fra-border-strong)", color: "var(--fra-muted)" }}
            >
              Keep it
            </button>
          </div>
        </form>
      )}
    </div>
  );
}

