import ConfigProvider from '../config-provider';
import React, { Component, ReactElement, isValidElement } from 'react';
import cls from 'classnames';
import { CommonProps } from '../types';
import { MessageQuickProps, MessageProps as NextMessageProps } from '@alifd/next/types/message';
import { Message as NextMessage } from '@alifd/next';

interface MessageProps extends NextMessageProps, CommonProps {
  bgcolor?: string;
}

function isMessageQuickProps(config: any): config is MessageQuickProps {
  return typeof config === 'object' && !isValidElement(config);
}

class Message extends Component<MessageProps> {
  static wrapMethod = (type?: 'notice' | 'success' | 'warning' | 'error' | 'help' | 'loading' | 'hide' | 'show') => (
    config?: string | MessageQuickProps | ReactElement,
  ) => {
    if (isMessageQuickProps(config)) {
      const { prefix = 'next-', closeable, content, className } = config;
      if (type === 'show') {
        config.type = (config.type === 'notice' ? 'help' : config.type);
      }

      config.className = cls(className, {
        [`${prefix}close-add`]: closeable === true,
        [`${prefix}with-content`]: content,
      });
    }
    const ret = NextMessage[type](config);
    return ret;
  };

  static notice = Message.wrapMethod('notice');
  static show = Message.wrapMethod('show');
  static success = Message.wrapMethod('success');
  static warning = Message.wrapMethod('warning');
  static error = Message.wrapMethod('error');
  static help = Message.wrapMethod('help');
  static loading = Message.wrapMethod('loading');
  static hide = Message.wrapMethod('hide');
  // @ts-ignore
  static withContext = NextMessage.withContext;

  classNameDefine = () => {
    let className_new;
    const {
      shape,
      prefix = 'next-',
      bgcolor = 'colorful',
      className,
    } = this.props;

    if (shape === 'toast') {
      const { bgcolor = 'white' } = this.props;
      className_new = cls(className, {
        [`${prefix}bg-white`]: bgcolor === 'white',
        [`${prefix}bg-colorful`]: bgcolor === 'colorful',
      });
    }

    className_new = cls(className, {
      [`${prefix}bg-white`]: bgcolor === 'white',
      [`${prefix}bg-colorful`]: bgcolor === 'colorful',
    });

    return className_new;
  };

  render() {
    const {
      shape,
      type,
      prefix = 'next-',
      ...otherProps
    } = this.props;

    return (
      <NextMessage
        type = {type === 'notice' ? 'help' : type}
        {...otherProps}
        shape={shape}
        prefix={prefix}
        className={this.classNameDefine()}
      />
    );
  }
}

export default ConfigProvider.config(Message);
