import React, { type ReactNode } from "react";

const h = React.createElement;

function joinClassNames(...values: Array<string | undefined | null | false>): string {
  return values.filter(Boolean).join(" ");
}

export interface UniDeskDialogProps {
  title: ReactNode;
  children?: ReactNode;
  actions?: ReactNode;
  onClose: () => void;
  className?: string;
  backdropClassName?: string;
  bodyClassName?: string;
  actionsClassName?: string;
  titleId?: string;
  testId?: string;
  closeTestId?: string;
  closeLabel?: string;
  disableClose?: boolean;
  closeOnBackdrop?: boolean;
}

export function UniDeskDialog({
  title,
  children,
  actions,
  onClose,
  className,
  backdropClassName,
  bodyClassName,
  actionsClassName,
  titleId,
  testId,
  closeTestId,
  closeLabel = "关闭",
  disableClose = false,
  closeOnBackdrop = true,
}: UniDeskDialogProps) {
  const sectionProps: Record<string, unknown> = {
    className: joinClassNames("raw-dialog", "unidesk-dialog", className),
    role: "dialog",
    "aria-modal": "true",
  };
  if (titleId) {
    sectionProps["aria-labelledby"] = titleId;
  } else if (typeof title === "string") {
    sectionProps["aria-label"] = title;
  }
  if (testId) sectionProps["data-testid"] = testId;

  return h("div", {
    className: joinClassNames("modal-backdrop", "unidesk-dialog-backdrop", backdropClassName),
    role: "presentation",
    onClick: (event: React.MouseEvent<HTMLElement>) => {
      if (closeOnBackdrop && !disableClose && event.target === event.currentTarget) onClose();
    },
  },
    h("section", sectionProps,
      h("div", { className: "raw-dialog-head unidesk-dialog-head" },
        h("strong", titleId ? { id: titleId } : null, title),
        h("button", { type: "button", className: "ghost-btn", onClick: onClose, disabled: disableClose, "data-testid": closeTestId }, closeLabel),
      ),
      h("div", { className: joinClassNames("unidesk-dialog-body", bodyClassName) }, children),
      actions ? h("div", { className: joinClassNames("unidesk-dialog-actions", actionsClassName) }, actions) : null,
    ),
  );
}
