import { xpayShadowRoot } from "@src/config";
import { MouseEvent, ReactElement } from "react";
import { createPortal } from "react-dom";

export type TxModalType =
  | "neutral"
  | "waiting"
  | "warning"
  | "error"
  | "success";

type Props = {
  id: string;
  children: ReactElement | ReactElement[];
  onCloseClick: () => void;
  type?: TxModalType;
  className?: string;
};

export const TxModal = ({
  id,
  children,
  onCloseClick,
  type = "waiting",
  className,
}: Props) => {
  const onBackdropClick = (e: MouseEvent<HTMLDivElement>) => {
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
    if (e.target === e.currentTarget) {
      onCloseClick();
    }
  };

  return createPortal(
    <div
      className="fixed box-border inset-0 z-20 flex items-center justify-center bg-black bg-opacity-80"
      onMouseDown={onBackdropClick}
    >
      <div
        className={`relative bg-t_bg_primary rounded-3xl p-4 w-full min-w-[340px] overflow-auto max-w-x_modal border-2 ${
          type === "error"
            ? "border-t_error_dark"
            : type === "success"
            ? "border-t_success_dark"
            : type === "warning"
            ? "border-t_warning_dark"
            : type === "waiting"
            ? "border-t_main_accent_dark"
            : "border-t_text_primary border-opacity-10"
        } ${className}`}
      >
        {children}
      </div>
    </div>,
    xpayShadowRoot!,
    id,
  );
};
