import * as React from 'react';
import classnames from 'classnames';
import { messageProps, configProps } from 'src/types/op-message';
import { SuccessIcon, WarnIcon, ErrorIcon } from '../common-view';
import Layout from '../op-layout';
import event from '../event';
import PlaySound from '../op-play-sound/index';

import './index.scss';

const { Content, Left, Right } = Layout;

export const styleConfig = {
  success: {
    icon: <SuccessIcon color='#fff' />,
    style: {
      'background-color': '#00bf29',
      color: '#ffffff',
    },
  },
  warning: {
    icon: <WarnIcon color='#000' />,
    style: {
      'background-color': '#ffd119',
      color: '#000000',
    },
  },
  error: {
    icon: <ErrorIcon color='#fff' />,
    style: {
      'background-color': '#FE3824',
      color: '#ffffff',
    },
  },
};

export default function Message(props: messageProps) {
  const {
    visible,
    type = 'success',
    title,
    subTitle,
    right,
    left,
    content,
    onChange,
    customConfig,
    style,
    className,
  } = props;

  const mergedConfig = {
    ...styleConfig,
    ...(customConfig || {}),
  };

  const bindEsc = React.useCallback(() => {
    onChange(false);
  }, []);

  React.useEffect(() => {
    if (visible) {
      event.bind('esc', bindEsc);
    } else {
      event.unbind('esc', bindEsc);
    }
    return () => {
      event.unbind('esc', bindEsc);
    };
  }, [visible]);

  const config = (mergedConfig[type] || mergedConfig.success) as configProps;
  const newStyle = { ...style, ...config.style } as React.CSSProperties;

  return visible ? (
    <>
      <PlaySound type={type} autoPlay volume={1} />
      <Layout
        style={newStyle}
        className={classnames('op-message-container', className)}
      >
        <Left middle>
          {left || <div className='op-message-icon'>{config.icon}</div>}
        </Left>
        {content || (
          <Content middle className='op-message-msg'>
            <div className='op-message-msg__title'>{title}</div>
            <div className='op-message-msg__subtitle'>{subTitle}</div>
          </Content>
        )}
        <Right
          data-hottag='cn-op.message-close'
          onClick={() => {
            onChange(false);
          }}
        >
          {right || (
            <div className='op-message-container__right'>关闭&ensp;[Esc]</div>
          )}
        </Right>
      </Layout>
    </>
  ) : null;
}
