import React from 'react'
import ReactDom from 'react-dom'
import Toast from './toast'

interface ToastProps {
  content?: string | React.ReactNode
  duration?: number
  mask?: boolean
  position?: 'bottom' | 'middle' | 'top'
  contentStyle?: any
  top?: number
  messageType?: 'info' | 'fail' | 'success' | 'warn'
  onClose?(): void
}

interface ToastConfig extends ToastProps {
  type: string
}
interface ToastConfigKey extends ToastConfig {
  id: number
}

let messageArgs: ToastConfigKey[] = []
const createToast = () => {
  const createDom = document.createElement('div')
  document.body.appendChild(createDom)
  createDom.setAttribute('class', 'toast')
  const renderToast = (props: ToastConfig) => {
    if (props.type === 'message') {
      messageArgs.push({...props, id: Math.random()})
      return ReactDom.render(
        messageArgs.map((item,index) => (
          <Toast {...item} destroyDom={() => destroyToast(item.id)} key={item.id} type="message" />
        )),
        createDom
      )
    }
    return ReactDom.render(<Toast {...props} />, createDom)
  }
  return {
    addToast: (props: ToastConfig) => {
      renderToast(props)
    },
  }
}
const destroyToast = (id: number) => {
  messageArgs = messageArgs.filter(item => item.id === id)
}
let firstToast: {addToast(props: ToastConfig): void; destroyToast?(): void}
const toast = (props: ToastConfig) => {
  if (!firstToast) {
    firstToast = createToast()
  }
  firstToast.addToast(props)
}

const success = (ToastProp?: ToastProps): void => toast({type: 'success', ...ToastProp})

const fail = (ToastProp?: ToastProps): void => toast({type: 'fail', ...ToastProp})

const info = (ToastProp?: ToastProps): void => toast({type: 'info', ...ToastProp})

const message = (ToastProp?: ToastProps): void => toast({type: 'message', ...ToastProp})

const loading = (ToastProp?: ToastProps): void => toast({type: 'loading', ...ToastProp})

const hide = (): void => toast({type: 'hide'})

export default {
  success,
  fail,
  info,
  loading,
  hide,
  message,
}
