"use client";

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

import { toast } from "@/lib/toast";
import { requestSupportCancel, requestSupportChange } from "@/services/employee-requests/employee-requests.client";
import type { CancelOptions, MyRequestRow } from "@/services/employee-requests/employee-requests.types";
import { fraButton } from "./fra-primitives";

/**
 * LEIS-1052 — the form for asking support to change, or cancel, a booking.
 *
 * Opened from "Request change" / "Request cancellation" with the type already set by the button.
 * It collects a reason (always), what to change (changes only) and optional notes, and shows the
 * booking so the person can see what they are asking about. For a cancellation it says that fees may
 * apply under the fare rules or cancellation terms: support, not this form, decides the amount.
 *
 * The submit button names the route the request will take, because that is the one thing the person
 * cannot see otherwise:
 *   "Send to admin for approval"  the booking was approved by an admin, who decides first
 *   "Send to support"             nobody to approve it, it goes straight to leisure.com support
 *
 * A native <dialog> for the same reasons as the instant-cancel dialog: top layer, focus trap, Escape,
 * and no z-index fight. Escape and the backdrop are ignored while the request is in flight.
 */

export type SupportRequestKind = "CHANGE" | "CANCELLATION";

const CHANGE_HINT: Record<"FLIGHT" | "HOTEL", string> = {
  FLIGHT: "New dates, times or flights, for example: move to 25 Oct, any morning flight.",
  HOTEL: "New dates or room, for example: check in 26 Oct instead, a king room.",
};

function bookingSummary(row: MyRequestRow): string {
  if (row.trip.flight) return `${row.trip.flight.origin} → ${row.trip.flight.destination}`;
  if (row.trip.hotel) return row.trip.hotel.property;
  return row.reference;
}

export function submitLabel(route: CancelOptions["submitRoute"]): string {
  return route === "ADMIN_THEN_SUPPORT" ? "Send to admin for approval" : "Send to support";
}

interface SupportRequestDialogProps {
  row: MyRequestRow;
  options: CancelOptions;
  kind: SupportRequestKind;
  open: boolean;
  onClose: () => void;
}

export function SupportRequestDialog({ row, options, kind, open, onClose }: SupportRequestDialogProps) {
  const ref = useRef<HTMLDialogElement>(null);
  const queryClient = useQueryClient();
  const [reason, setReason] = useState("");
  const [changeDetails, setChangeDetails] = useState("");
  const [notes, setNotes] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<{ code?: string; message: string } | null>(null);

  useEffect(() => {
    const dialog = ref.current;
    if (!dialog) return;
    if (open && !dialog.open) {
      setError(null);
      dialog.showModal();
    } else if (!open && dialog.open) {
      dialog.close();
    }
  }, [open]);

  const isChange = kind === "CHANGE";
  const ready = reason.trim().length > 0 && (!isChange || changeDetails.trim().length > 0);

  const submit = async () => {
    if (!ready || busy) return;
    setBusy(true);
    setError(null);
    const res = isChange
      ? await requestSupportChange(row.id, {
          reason: reason.trim(),
          changeDetails: changeDetails.trim(),
          ...(notes.trim() ? { notes: notes.trim() } : {}),
        })
      : await requestSupportCancel(row.id, { reason: reason.trim(), ...(notes.trim() ? { notes: notes.trim() } : {}) });
    setBusy(false);

    if (!res.success) {
      // The answer may have changed what the buttons should be (window open after all, already with support).
      void queryClient.invalidateQueries({ queryKey: ["employee-requests"] });
      setError({ code: res.code, message: res.message ?? "We couldn't send your request. Please try again." });
      return;
    }

    toast.success(
      res.data?.route === "ADMIN_THEN_SUPPORT"
        ? "Request sent. Your admin will review it first."
        : "Request sent to leisure.com support. Updates come by email.",
    );
    setReason("");
    setChangeDetails("");
    setNotes("");
    await queryClient.invalidateQueries({ queryKey: ["employee-requests"] });
    onClose();
  };

  const field = "w-full resize-y rounded-[10px] px-[12px] py-[10px] text-[14px] disabled:opacity-60";
  const fieldStyle = {
    border: "1px solid var(--fra-border-strong)",
    backgroundColor: "var(--fra-surface)",
    color: "var(--fra-text)",
  } as const;
  const label = "mb-[6px] block text-[13px] font-semibold";

  return (
    <dialog
      ref={ref}
      aria-labelledby={`support-title-${row.id}`}
      onCancel={(e) => {
        if (busy) e.preventDefault();
        else onClose();
      }}
      onClick={(e) => {
        if (e.target === ref.current && !busy) onClose();
      }}
      className="m-auto w-[min(94vw,520px)] rounded-[16px] border-0 p-0 shadow-[0_20px_60px_rgba(15,39,51,0.3)] backdrop:bg-[rgba(15,39,51,0.45)]"
    >
      <form
        className="p-[24px]"
        style={{ color: "var(--fra-text)" }}
        onSubmit={(e) => {
          e.preventDefault();
          void submit();
        }}
      >
        <h2 id={`support-title-${row.id}`} className="m-0 text-[18px] font-extrabold" style={{ color: "var(--fra-heading)" }}>
          {isChange ? "Request a change" : "Request a cancellation"}
        </h2>

        <div
          className="mt-[14px] rounded-[10px] px-[14px] py-[12px] text-[14px]"
          style={{ backgroundColor: "var(--fra-surface-2)", border: "1px solid var(--fra-border)" }}
        >
          <div className="font-semibold" style={{ color: "var(--fra-heading)" }}>
            {bookingSummary(row)}
          </div>
          <div className="text-[13px]" style={{ color: "var(--fra-muted)" }}>
            {row.reference}
          </div>
        </div>

        {!isChange && (
          <p className="m-0 mt-[12px] text-[13px]" style={{ color: "var(--fra-muted)" }}>
            Fees may apply under the {options.type === "FLIGHT" ? "fare rules" : "cancellation terms"}. Support will tell you the
            amount by email before anything is final.
          </p>
        )}

        <div className="mt-[16px]">
          <label htmlFor={`support-reason-${row.id}`} className={label}>
            Reason <span style={{ color: "var(--fra-coral)" }}>*</span>
          </label>
          <textarea
            id={`support-reason-${row.id}`}
            value={reason}
            onChange={(e) => setReason(e.target.value)}
            rows={2}
            maxLength={5000}
            disabled={busy}
            className={field}
            style={fieldStyle}
          />
        </div>

        {isChange && (
          <div className="mt-[14px]">
            <label htmlFor={`support-change-${row.id}`} className={label}>
              What to change <span style={{ color: "var(--fra-coral)" }}>*</span>
            </label>
            <textarea
              id={`support-change-${row.id}`}
              value={changeDetails}
              onChange={(e) => setChangeDetails(e.target.value)}
              rows={3}
              maxLength={5000}
              disabled={busy}
              placeholder={CHANGE_HINT[options.type]}
              className={field}
              style={fieldStyle}
            />
          </div>
        )}

        <div className="mt-[14px]">
          <label htmlFor={`support-notes-${row.id}`} className={label}>
            Notes <span className="font-normal" style={{ color: "var(--fra-muted)" }}>(optional)</span>
          </label>
          <textarea
            id={`support-notes-${row.id}`}
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            rows={2}
            maxLength={5000}
            disabled={busy}
            className={field}
            style={fieldStyle}
          />
        </div>

        {error && (
          <div
            role="alert"
            className="mt-[14px] rounded-[10px] px-[12px] py-[10px] text-[13px]"
            style={{ backgroundColor: "var(--fra-rejected-bg)", color: "var(--fra-rejected)" }}
          >
            {error.message}
          </div>
        )}

        <div className="mt-[20px] flex flex-wrap justify-end gap-[8px]">
          <button type="button" onClick={onClose} disabled={busy} className={fraButton.ghost}>
            Cancel
          </button>
          <button type="submit" disabled={!ready || busy} className={`${fraButton.primary} disabled:cursor-not-allowed disabled:opacity-50`}>
            {busy ? "Sending…" : submitLabel(options.submitRoute)}
          </button>
        </div>
      </form>
    </dialog>
  );
}
