"use client";

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

import { toast } from "@/lib/toast";
import {
  actionsFor,
  noActionsReason,
  type RequestAction,
} from "@/services/employee-requests/request-actions";
import {
  cancelDirect,
  requestCancellation,
  requestChange,
  resubmitRequest,
  withdrawRequest,
} from "@/services/employee-requests/employee-requests.client";
import type { MyRequestRow } from "@/services/employee-requests/employee-requests.types";
import { fraButton } from "./fra-primitives";

/**
 * The buttons a requester can press on their own request (LEIS-1013).
 *
 * Which buttons appear is `actionsFor(row)`'s decision, never this
 * component's — see that file for the status table and why it is shared.
 *
 * ── Why everything confirms in place rather than in a dialog ────────────
 *
 * Four of the five actions need a sentence from the user anyway ("say what has
 * changed", "why does this need cancelling"), so a confirmation dialog would
 * be a second modal on top of a card that is already inside one on some
 * screens. Expanding a small form under the button is one interaction instead
 * of two, keeps the request itself visible while you write the reason, and
 * does not fight the SRP's Bootstrap for z-index.
 *
 * Withdraw takes no reason but still confirms, because it is terminal.
 *
 * ── Why the whole list is invalidated, not patched ──────────────────────
 *
 * The server decides what a request becomes: a reply flips INFO_REQUESTED to
 * PENDING, a cancellation adds a row to `relatedRequests` that changes which
 * buttons are legal next. Patching a status locally would mean re-deriving all
 * of that on the client and getting it subtly wrong. `["employee-requests",
 * "mine"]` is the key both the home page and My requests read through — see
 * `useMyRequests`.
 */
/**
 * `hideKinds` (LEIS-1034) drops specific actions after `actionsFor` has
 * already decided them — used for exactly one case: a flight past its
 * free-cancellation window on a no-approval booking, where `cancel_direct`
 * would 409 `MANUAL_REVIEW_REQUIRED` on press. Everything else about the row
 * (Change, Edit, Withdraw…) stays offered; this never hides more than the
 * caller names.
 */
export function RequestActions({
  row,
  hideKinds,
}: {
  row: MyRequestRow;
  hideKinds?: RequestAction["kind"][];
}) {
  const actions = actionsFor(row).filter((action) => !hideKinds?.includes(action.kind));
  const reason = noActionsReason(row);
  const queryClient = useQueryClient();

  const [open, setOpen] = useState<RequestAction | null>(null);
  const [text, setText] = useState("");
  const [busy, setBusy] = useState(false);

  if (actions.length === 0) {
    return reason ? (
      <p className="m-0 mt-[12px] text-[13px]" style={{ color: "var(--fra-muted)" }}>
        {reason}
      </p>
    ) : null;
  }

  const close = () => {
    setOpen(null);
    setText("");
  };

  const run = async (action: RequestAction) => {
    const trimmed = text.trim();
    if (action.requiresReason && !trimmed) return;
    setBusy(true);

    const result = await send(action, row.id, trimmed);

    setBusy(false);
    if (!result.success) {
      // The server's own message, which says WHY — "this request can no longer
      // be withdrawn", "there is already a change waiting". Far better than a
      // generic failure, and the 409s are the cases a user actually hits.
      toast.error(result.message ?? "That did not work. Please try again.");
      return;
    }

    toast.success(SUCCESS[action.kind]);
    close();
    await queryClient.invalidateQueries({ queryKey: ["employee-requests", "mine"] });
  };

  return (
    <div className="mt-[16px]">
      <div className="flex flex-wrap items-center gap-[8px]">
        {actions.map((action) => (
          <button
            key={action.kind + action.label}
            type="button"
            onClick={() => {
              if (action.kind === "edit") {
                // Editing a trip means choosing a different flight, which is
                // the search and the request overlay — not a text box. Until
                // that flow accepts an existing request id, this says so
                // rather than opening a form that cannot do the job.
                toast.info("Editing a trip is coming soon. Withdraw and search again for now.");
                return;
              }
              setOpen(open?.kind === action.kind ? null : action);
              setText("");
            }}
            aria-expanded={open?.kind === action.kind}
            className={action.destructive ? DESTRUCTIVE : fraButton.ghost}
          >
            {action.label}
          </button>
        ))}
      </div>

      {open && (
        <form
          className="mt-[12px] rounded-[10px] p-[12px]"
          style={{
            backgroundColor: "var(--fra-surface-2)",
            border: "1px solid var(--fra-border)",
          }}
          onSubmit={(e) => {
            e.preventDefault();
            void run(open);
          }}
        >
          {open.prompt && (
            <p className="m-0 mb-[8px] text-[13px]" style={{ color: "var(--fra-text)" }}>
              {open.prompt}
            </p>
          )}

          {open.requiresReason && (
            <textarea
              value={text}
              onChange={(e) => setText(e.target.value)}
              rows={3}
              maxLength={5000}
              autoFocus
              disabled={busy}
              aria-label={open.prompt ?? open.label}
              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 items-center gap-[8px]">
            <button
              type="submit"
              disabled={busy || (open.requiresReason && !text.trim())}
              className={`${open.destructive ? DESTRUCTIVE : fraButton.primary} disabled:cursor-not-allowed disabled:opacity-50`}
            >
              {busy ? "Working…" : CONFIRM[open.kind]}
            </button>
            <button type="button" onClick={close} disabled={busy} className={fraButton.ghost}>
              Keep it as it is
            </button>
          </div>
        </form>
      )}
    </div>
  );
}

const DESTRUCTIVE =
  "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)]";

/** Button copy at the point of no return, naming the act rather than "Confirm". */
const CONFIRM: Record<string, string> = {
  withdraw: "Withdraw this request",
  resubmit: "Send it back",
  change: "Send change request",
  cancellation: "Request cancellation",
  cancel_direct: "Cancel this trip",
  edit: "Save changes",
};

const SUCCESS: Record<string, string> = {
  withdraw: "Request withdrawn.",
  resubmit: "Sent back to your approver.",
  change: "Change requested — your approver has been notified.",
  cancellation: "Cancellation requested — your approver has been notified.",
  cancel_direct: "Trip cancelled and refunded.",
  edit: "Request updated.",
};

function send(action: RequestAction, id: string, reason: string) {
  switch (action.kind) {
    case "withdraw":
      return withdrawRequest(id, reason || undefined);
    case "resubmit":
      return resubmitRequest(id, reason);
    case "change":
      return requestChange(id, reason);
    case "cancellation":
      return requestCancellation(id, reason);
    case "cancel_direct":
      return cancelDirect(id, reason);
    default:
      // `edit` is intercepted before it reaches here.
      return Promise.resolve({ success: false, status: 0, message: "Not available yet." });
  }
}
