import { Alert as OldAlert, AlertProps, ConfigProvider } from 'antd';
import React, { useContext, useMemo } from 'react';
import './index.less';
import classNames from 'classnames';
import { Icon } from '../Icon';

interface AlertExtraProps extends AlertProps {
  titleAction?: React.ReactNode;
  descriptionAction?: React.ReactNode;
}

const Alert: React.FC<AlertProps & AlertExtraProps> = (props) => {
  // 为了与 antd 的生态保持兼容性，我们要求必须要使用 `.@{ant-prefix}` 变量来生成类名
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('btri-alert');

  const { type, icon, closeIcon } = props;

  const newIcon = useMemo(() => {
    if (icon) {
      return icon;
    }
    const icons = {
      info: 'AttentionRectangle',
      success: 'CheckOnSquare',
      warning: 'Caution',
      error: 'ErrorDiamond',
    };
    return <Icon iconName={icons[type]} style={{ marginRight: '8px' }}></Icon>;
  }, [type, icon]);

  const newCloseIcon = useMemo(() => {
    if (closeIcon) {
      return closeIcon;
    }
    return <Icon iconName={'CloseSmall'}></Icon>;
  }, [closeIcon]);

  const newMsg = useMemo(() => {
    return (
      <>
        {props.message}
        <div style={{ marginLeft: '16px' }}>{props.titleAction}</div>
      </>
    );
  }, [props.message, props.titleAction]);

  const newDescription = useMemo(() => {
    return (
      props.description && (
        <>
          {props.description}
          {props.descriptionAction && (
            <div style={{ marginLeft: '8px' }}>{props.descriptionAction}</div>
          )}
        </>
      )
    );
  }, [props.description, props.descriptionAction]);

  return (
    <OldAlert
      {...props}
      className={classNames(
        `${prefixCls}-box`,
        props.description && `${prefixCls}-has-description`,
        props.className,
      )}
      icon={newIcon}
      closeIcon={newCloseIcon}
      message={newMsg}
      description={newDescription}
    ></OldAlert>
  );
};

export { Alert };
