import React, { useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";

/**
 * Expandable FAB menu for document form actions.
 * Portaled to document.body so position:fixed stays viewport-fixed
 * even when portal-main / page enter animations use transform.
 */
export default function DocumentFloatingActions({
  onBack,
  showStartWork = false,
  startingWork = false,
  showSave = false,
  showComplete = false,
  saving = false,
  orderDirty = false,
  completedDoc = false,
  onStartWork,
  onSave,
  onComplete,
  onAddPage,
  onCopyPage,
  pageActionsDisabled = false,
}) {
  const [open, setOpen] = useState(false);
  const rootRef = useRef(null);
  const busy = saving || startingWork;

  const close = useCallback(() => setOpen(false), []);

  const runAction = useCallback(
    (action) => {
      action();
      close();
    },
    [close]
  );

  useEffect(() => {
    if (!open) return undefined;

    const onPointerDown = (event) => {
      if (rootRef.current?.contains(event.target)) return;
      close();
    };

    const onKeyDown = (event) => {
      if (event.key === "Escape") close();
    };

    document.addEventListener("pointerdown", onPointerDown);
    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("pointerdown", onPointerDown);
      document.removeEventListener("keydown", onKeyDown);
    };
  }, [open, close]);

  const saveLabel = saving
    ? "Saving…"
    : completedDoc
      ? orderDirty
        ? "Save changes & order"
        : "Save changes"
      : orderDirty
        ? "Save draft & order"
        : "Save draft";

  const actions = [
    {
      key: "back",
      label: "← Back",
      variant: "ghost",
      onClick: () => runAction(onBack),
    },
    showStartWork
      ? {
          key: "start",
          label: startingWork ? "Updating…" : "Set to in process",
          variant: "primary",
          disabled: busy,
          onClick: () => runAction(onStartWork),
        }
      : null,
    showSave
      ? {
          key: "save",
          label: saveLabel,
          variant: showComplete ? "default" : "primary",
          disabled: busy,
          pendingOrder: orderDirty,
          onClick: () => runAction(onSave),
        }
      : null,
    showComplete
      ? {
          key: "submit",
          label: saving ? "Submitting…" : "Complete & submit",
          variant: "primary",
          disabled: busy,
          onClick: () => runAction(onComplete),
        }
      : null,
    {
      key: "add",
      label: "+ Add page",
      variant: "ghost",
      disabled: pageActionsDisabled,
      onClick: () => runAction(onAddPage),
    },
    {
      key: "copy",
      label: "Copy page",
      variant: "ghost",
      disabled: pageActionsDisabled,
      onClick: () => runAction(onCopyPage),
    },
  ].filter(Boolean);

  const ui = (
    <div
      ref={rootRef}
      className={`doc-floating-actions${open ? " doc-floating-actions--open" : ""}${
        orderDirty ? " doc-floating-actions--dirty" : ""
      }`}
    >
      {open ? (
        <div
          className="doc-floating-actions__backdrop"
          aria-hidden
          onClick={close}
        />
      ) : null}

      <div
        id="doc-floating-actions-menu"
        className="doc-floating-actions__menu"
        role="menu"
        aria-label="Document actions"
        aria-hidden={!open}
      >
        {orderDirty && showSave ? (
          <span className="doc-floating-actions__status" role="status">
            Unsaved order
          </span>
        ) : null}

        {actions.map((action) => (
          <button
            key={action.key}
            type="button"
            role="menuitem"
            className={[
              "doc-floating-actions__btn",
              action.variant === "primary"
                ? "doc-floating-actions__btn--primary"
                : action.variant === "ghost"
                  ? "doc-floating-actions__btn--ghost"
                  : "",
              action.pendingOrder ? "doc-floating-actions__btn--pending-order" : "",
            ]
              .filter(Boolean)
              .join(" ")}
            disabled={action.disabled}
            tabIndex={open ? 0 : -1}
            onClick={action.onClick}
          >
            {action.label}
          </button>
        ))}
      </div>

      <button
        type="button"
        className="doc-floating-actions__fab"
        aria-expanded={open}
        aria-controls="doc-floating-actions-menu"
        aria-label={open ? "Close document actions" : "Open document actions"}
        onClick={() => setOpen((value) => !value)}
      >
        <span className="doc-floating-actions__fab-icon" aria-hidden>
          {open ? "×" : "+"}
        </span>
        {orderDirty && showSave && !open ? (
          <span className="doc-floating-actions__fab-dot" aria-hidden />
        ) : null}
      </button>
    </div>
  );

  if (typeof document === "undefined") return null;
  return createPortal(ui, document.body);
}
