"use client";

import { useState } from "react";

import { useCancelOptions } from "@/services/employee-requests/useCancelOptions";
import type { MyRequestRow } from "@/services/employee-requests/employee-requests.types";
import type { RequestAction } from "@/services/employee-requests/request-actions";
import { InstantCancelDialog, windowLine } from "./InstantCancelDialog";
import { RequestActions } from "./RequestActions";
import { supportExplainer } from "./SupportBadge";
import { SupportRequestDialog, type SupportRequestKind } from "./SupportRequestDialog";

/**
 * LEIS-1049 — the actions on a booked trip, decided by the SERVER's answer
 * (GET /requests/:id/cancel-options), never by this component or by `actionsFor`.
 *
 *   free window open      Cancel (instant, full refund) + Request change
 *   free window closed    Request cancellation + Request change
 *   with support          no actions, and a line saying support has it
 *   change waiting on     no actions, and a line saying the admin has it
 *   the admin
 *   anything else         nothing (the traveller who did not book, a trip already cancelled or started)
 *
 * It only takes over when the backend says the new flow is switched on (`flowEnabled`). While the flow
 * is off, for a trip that is not booked, or if the lookup fails, it renders the existing
 * <RequestActions/> untouched, so nothing regresses before the whole flow is live.
 *
 * Each button opens a dialog with the booking and the details it needs; the server re-checks the rules
 * when the person confirms, so a window that closed in the meantime is caught there.
 */
export function BookedTripActions({
  row,
  hideKinds,
}: {
  row: MyRequestRow;
  hideKinds?: RequestAction["kind"][];
}) {
  const [dialog, setDialog] = useState<null | "cancel" | SupportRequestKind>(null);
  const booked = row.status === "BOOKED" && row.canAct;
  const query = useCancelOptions(row.id, booked);
  const options = query.data;

  // Not a booked trip the viewer can act on: the existing buttons, as before.
  if (!booked) return <RequestActions row={row} hideKinds={hideKinds} />;
  // Still asking the server: draw nothing for a moment rather than flash buttons that may be replaced.
  if (query.isLoading) return null;
  // The lookup failed, or the new flow is off: keep the existing behaviour.
  if (!options || !options.flowEnabled || !options.viewer.isRequester) {
    return <RequestActions row={row} hideKinds={hideKinds} />;
  }

  const note = (text: string) => (
    <p className="m-0 mt-[12px] text-[13px]" style={{ color: "var(--fra-muted)" }}>
      {text}
    </p>
  );

  if (options.state === "WITH_SUPPORT") return note(supportExplainer());
  if (options.state === "REQUEST_OPEN") return note("Your request is waiting for your admin to review it.");
  if (options.state !== "ACTIONABLE") return null;

  const has = (a: (typeof options.actions)[number]) => options.actions.includes(a);
  const ghost =
    "inline-flex h-11 items-center gap-2 rounded-[var(--fra-radius-sm)] border border-[var(--fra-border-strong)] px-[16px] text-sm font-semibold text-[var(--fra-text)] transition-colors hover:bg-[var(--fra-hover)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--fra-navy-2)]";
  const danger =
    "inline-flex h-11 items-center gap-2 rounded-[var(--fra-radius-sm)] border border-[var(--fra-rejected-solid)] px-[16px] text-sm font-semibold text-[var(--fra-rejected-solid)] transition-colors hover:bg-[var(--fra-rejected-bg)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--fra-rejected-solid)]";

  return (
    <>
      <div className="mt-[16px] flex flex-wrap items-center gap-[10px]">
        {has("CANCEL_NOW") && (
          <button type="button" onClick={() => setDialog("cancel")} className={danger}>
            Cancel
          </button>
        )}
        {has("REQUEST_CANCELLATION") && (
          <button type="button" onClick={() => setDialog("CANCELLATION")} className={danger}>
            Request cancellation
          </button>
        )}
        {has("REQUEST_CHANGE") && (
          <button type="button" onClick={() => setDialog("CHANGE")} className={ghost}>
            Request change
          </button>
        )}
      </div>
      {has("CANCEL_NOW") && note(windowLine(options))}
      {has("REQUEST_CANCELLATION") && note("The free cancellation window has ended. Support will confirm any fee before it is final.")}

      <InstantCancelDialog row={row} options={options} open={dialog === "cancel"} onClose={() => setDialog(null)} />
      <SupportRequestDialog
        row={row}
        options={options}
        kind={dialog === "CHANGE" ? "CHANGE" : "CANCELLATION"}
        open={dialog === "CHANGE" || dialog === "CANCELLATION"}
        onClose={() => setDialog(null)}
      />
    </>
  );
}
