import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/* eslint-disable react/default-props-match-prop-types */

import React, { useContext, useEffect } from 'react';
import clsx from 'clsx';
import { Cross, Success } from '@react-vant/icons';
import Popup from '../popup';
import Loading from '../loading';
import { lockClick } from './lock-click';
import { isDef } from '../utils';
import ConfigProviderContext from '../config-provider/ConfigProviderContext'; // eslint-disable-next-line react/require-default-props

const Toast = props => {
  let clickable = false;
  const {
    prefixCls,
    createNamespace
  } = useContext(ConfigProviderContext);
  const [bem] = createNamespace('toast', prefixCls);

  const toggleClickable = () => {
    const newValue = props.visible && props.forbidClick;

    if (clickable !== newValue) {
      clickable = newValue;
      lockClick(clickable);
    }

    if (!props.visible) {
      lockClick(false);
    }
  };

  const onClick = () => {
    if (props.closeOnClick) {
      props.onClose();
    }
  };

  useEffect(() => {
    toggleClickable();
  }, [props.visible, props.forbidClick]);

  const renderIcon = () => {
    const {
      icon,
      type,
      iconSize,
      loadingType
    } = props;
    const hasIcon = icon || type === 'success' || type === 'fail';

    if (hasIcon) {
      const buildInIcon = type === 'fail' ? _jsx(Cross, {}) : _jsx(Success, {});
      return React.cloneElement(icon || buildInIcon, {
        className: clsx(bem('icon')),
        fontSize: iconSize
      });
    }

    if (type === 'loading') {
      return _jsx(Loading, {
        className: clsx(bem('loading')),
        type: loadingType
      });
    }

    return null;
  };

  const renderMessage = () => {
    const {
      message
    } = props;

    if (isDef(message) && message !== '') {
      return _jsx("div", Object.assign({
        className: clsx(bem('info'))
      }, {
        children: message
      }));
    }

    return null;
  };

  return _jsxs(Popup, Object.assign({
    className: clsx([bem([props.position, {
      [props.type]: !props.icon
    }]), props.className]),
    visible: props.visible,
    overlay: props.overlay,
    transition: props.transition,
    overlayClass: props.overlayClass,
    overlayStyle: props.overlayStyle,
    closeOnClickOverlay: props.closeOnClickOverlay,
    lockScroll: false,
    onClick: onClick,
    onClose: props.onClose,
    onClosed: props.onClosed,
    onOpened: props.onOpened,
    teleport: props.teleport
  }, {
    children: [renderIcon(), renderMessage()]
  }));
};

Toast.defaultProps = {
  type: 'info',
  duration: 2000,
  position: 'middle',
  transition: 'rv-fade',
  loadingType: 'circular',
  overlay: false
};
export default Toast;