/**
 * global popup notification
 */
import React from 'react';
import ReactDOM from 'react-dom';
import { useTranslation } from 'react-i18next';
import iconWarning from '@/assets/icon/redError.svg';
import iconInfo from '@/assets/icon/blackInfo.svg';
import iconCheck from '@/assets/icon/greenCheck.svg';
import MessageBar from '@/components/Message/MessageBar';

export enum MessageTypes {
  Success = 'Success',
  Info = 'Info',
  Error = 'Error',
}

export interface MessageProps {
  content: Element | string;
  type: MessageTypes;
  i18?: boolean;
  isRichText?: boolean;
  actions: React.ReactNode;
}

const MessageBottomComp: React.FC<MessageProps> = ({
  content,
  type,
  i18,
  isRichText,
  actions,
}) => {
  const { t } = useTranslation();
  const getImgSrc = (type: MessageTypes): string => {
    let src = '';
    switch (type) {
      case MessageTypes.Error:
        src = iconWarning;
        break;
      case MessageTypes.Info:
        src = iconInfo;
        break;
      case MessageTypes.Success:
        src = iconCheck;
        break;
      default:
        src = iconInfo;
        break;
    }
    return src;
  };
  return (
    <MessageBar
      icon={getImgSrc(type)}
      tips={
        <div className="tipsContainer">
          <div
            // eslint-disable-next-line react/no-danger
            dangerouslySetInnerHTML={{
              __html:
                !isRichText && i18 ? t(content as string) : (content as string),
            }}
          />
        </div>
      }
      actions={actions}
    />
  );
};

const message = (props: MessageProps & { duration?: number }) => {
  const holder = document.createElement('div');
  holder.setAttribute('id', 'dataverseMessageBox');
  document.body.append(holder);
  const destroy = () => {
    holder.remove();
  };

  setTimeout(() => {
    destroy();
  }, props.duration || 3000);

  holder.addEventListener('click', () => {
    holder.remove();
  });
  ReactDOM.render(<MessageBottomComp {...props} />, holder);
};

export default message;
