import React, { useState } from 'react'
import { defaultTo, propOr } from 'ramda'

import MTToast from './mt-toast'
import MTAnimation from './mt-animation'
import useTimer from './use-timer'

const DEFAULT_TOAST_LIFETIME_SECONDS = 5
const defaultAnimations = {
  onOpen: 'fadeInTop',
  onClose: 'fadeOutRight',
}
const typeToColorMap = {
  info: 'grey',
  warning: 'yellow',
  error: 'red',
  success: 'green',
}

function ToastListItem (props) {
  const {
    toast,
    lifetime,
    animations,
    onDismissed,
  } = props
  const {
    id,
    type = 'info',
    description,
    actionItem,
    ...rest
  } = toast

  const color = typeToColorMap[type]

  const [ isDismissed, setIsDismissed ] = useState(false)

  const dismiss = () => {
    if (!isDismissed) {
      setIsDismissed(true)
      onDismissed(id)
    }
  }

  const {
    pause: pauseTimer,
    resume: resumeTimer,
    clear: clearTimer,
  } = useTimer(lifetime * 1000, dismiss)

  const handleClose = () => {
    clearTimer()
    dismiss()
  }

  return (
    <MTAnimation
      show={ !isDismissed }
      enterAnimationClass={ animations.onEnter }
      leaveAnimationClass={ animations.onClose }
      leaveDuration="short"
    >
      <MTToast
        color={ color }
        { ...rest }
        onClose={ handleClose }
        onMouseEnter={ () => pauseTimer() }
        onMouseLeave={ () => resumeTimer() }
      >
        { description &&
        <span className="mt-toast-list-item__description">{ description }</span>
          }
        { actionItem && (
        <div className="mt-toast-list-item__action">
          { actionItem }
        </div>
        ) }
      </MTToast>
    </MTAnimation>
  )
}

function MTToastList (props) {
  const {
    toasts = [],
    lifetime = DEFAULT_TOAST_LIFETIME_SECONDS,
    onToastDismissed = () => {},
  } = props

  const animations = propOr(defaultAnimations, 'animations', props)

  return (
    <div className="mt-toast-list">
      { toasts.map((toast) => {
        const toastLifetime = defaultTo(lifetime, toast.lifetime)

        return (
          <ToastListItem
            toast={ toast }
            lifetime={ toastLifetime }
            animations={ animations }
            onDismissed={ onToastDismissed }
            key={ toast.id }
          />
        )
      }) }
    </div>
  )
}

export default MTToastList
