import { Modal as AntdModal, ModalProps } from "antd";
import { HookAPI } from "antd/es/modal/useModal";
import classNames from "classnames";
import React, { useMemo } from "react";
import { TYIcon } from "../../TYIcon";
import { tyButtonDangerWrapperCls, tyButtonWrapperCls } from "../Button/styled";
import { tyModalCls } from "./styled";
// import { myRoot } from '../../../util/constant';

let internalModal: HookAPI | undefined;

export function setInternalModal(value: HookAPI | undefined) {
  internalModal = value;
}

export type { ModalFuncProps, ModalProps } from "antd";

export const Modal = (props: ModalProps) => {
  const { className, footer, ...restProps } = props;
  const realFooter = useMemo<ModalProps["footer"]>(() => {
    if (footer !== undefined) {
      return footer;
    }

    return (_node, { OkBtn, CancelBtn }) => {
      const wrapperCls = classNames(tyButtonWrapperCls);
      return (
        <div className={wrapperCls}>
          <CancelBtn />
          <OkBtn />
        </div>
      );
    };
  }, [footer]);
  return (
    <AntdModal className={classNames(tyModalCls, className)} footer={realFooter} {...restProps} />
  );
};

type ModalFunc = (typeof AntdModal)["success"];
type Params = Parameters<ModalFunc>;
type ModalFuncProps = Params[0];

const wrapperModalFunc =
  (type: "success" | "info" | "error" | "warning" | "confirm", params: Partial<ModalFuncProps>) =>
  (props: ModalFuncProps) => {
    const { className, closeIcon, icon, ...restProps } = props;
    const myIcon = closeIcon ? <></> : icon;

    const passParams: ModalFuncProps = {
      ...params,
      icon: myIcon,
      centered: true,
      closable: true,
      className: classNames(tyModalCls, className),
      closeIcon: <TYIcon className={"closeIcon"} type="icon-x-01" />,
      footer: (_node, { OkBtn, CancelBtn }) => {
        const wrapperCls = classNames(tyButtonWrapperCls, {
          [tyButtonDangerWrapperCls]: ["error", "warning"].includes(type),
        });
        return (
          <div className={wrapperCls}>
            <CancelBtn />
            <OkBtn />
          </div>
        );
      },
      ...restProps,
    };

    if (internalModal) {
      return internalModal[type](passParams);
    } else {
      AntdModal[type](passParams);
    }
  };

Modal.success = wrapperModalFunc("success", {
  icon: <TYIcon type="tongyi-checkCircle-line" />,
});
Modal.info = wrapperModalFunc("info", {
  icon: <TYIcon type="tongyi-info-line" />,
});
Modal.error = wrapperModalFunc("error", {
  icon: <TYIcon type="tongyi-errorCircle-line" />,
});
Modal.warning = wrapperModalFunc("warning", {
  icon: <TYIcon type="tongyi-warningCircle-line" />,
});
Modal.confirm = wrapperModalFunc("confirm", {
  icon: <TYIcon type="tongyi-warningCircle-line" />,
});

Modal.Iconless = (props: ModalFuncProps) => {
  return Modal.warning({
    closeIcon: true,
    ...props,
  });
};
