import React, { useCallback, useMemo } from "react";

import { ModalActionsProps, ModalActionsButton } from "../interface";
import "./index.css";
import clsx from "clsx";

import Button from "@components/Button";

const cancelDefault = { variant: "contained", color: "gray", size: "medium", loading: false, disabled: false };

const confirmDefault = { variant: "contained", color: "primary", size: "medium", loading: false, disabled: false };

/**
 * ModalActions组件
 * ```
 */
const ModalActions: React.FC<ModalActionsProps> = props => {
  const { cancelText, okText, confirmConfig, cancelConfig, onCancel, onOk } = props;

  const hasCancelBtn = useMemo(() => !!cancelText, [cancelText]);

  const getButtonProps = useCallback((defaultConfig: ModalActionsButton, btnConfig?: ModalActionsButton) => {
    if (btnConfig) {
      return { ...defaultConfig, ...btnConfig };
    }

    return defaultConfig;
  }, []);

  /**取消按钮 */
  const renderCancelButton = useMemo(() => {
    return cancelText ? (
      <Button
        {...getButtonProps(cancelDefault as ModalActionsButton, cancelConfig)}
        className={clsx("nts-modal-actions-cancel", `${cancelConfig?.className || ""}`)}
        onClick={onCancel}
      >
        {cancelText}
      </Button>
    ) : null;
  }, [cancelText, cancelConfig, onCancel]);

  /**确认按钮 */
  const renderConfirmButton = useMemo(() => {
    return okText ? (
      <Button
        {...getButtonProps(confirmDefault as ModalActionsButton, confirmConfig)}
        className={clsx("nts-modal-actions-confirm", `${confirmConfig?.className || ""}`, { ["ml-4"]: hasCancelBtn })}
        onClick={onOk}
      >
        {okText}
      </Button>
    ) : null;
  }, [okText, confirmConfig, hasCancelBtn, onOk]);

  return (
    <div className={clsx("nts-modal-actions", props.className || "")}>
      {renderCancelButton}
      {renderConfirmButton}
    </div>
  );
};

ModalActions.defaultProps = {
  cancelConfig: { variant: "contained", color: "gray", size: "medium", loading: false, disabled: false },
  confirmConfig: { variant: "contained", color: "primary", size: "medium", loading: false, disabled: false }
};

export { ModalActionsProps };

export default ModalActions;
