import React, { useState, useEffect, useMemo, useRef } from 'react'
import { Progress } from 'antd'
import './index.less'

function ProgressComponent({ status }) {
  const timer = useRef(null)
  const currentStatus = useRef('loading')
  const [percent, setPersent] = useState(0)
  const isHide = useMemo(() => percent === 100, [percent])

  useEffect(() => {
    if (percent < 80 && currentStatus.current === 'loading') {
      const num = percent + 20
      timer.current = setTimeout(() => setPersent(num), 200)
    }
  }, [percent])

  useEffect(() => {
    if (currentStatus.current !== status) {
      clearTimeout(timer.current)
      currentStatus.current = status
      const isOver = status === 'error' || status === 'over'
      setPersent(isOver ? 100 : 20)
    }
  }, [status])

  useEffect(() => {
    return () => clearTimeout(timer.current)
  })
  return (
    <Progress
      status={status === 'error' ? 'exception' : 'active'}
      percent={percent}
      showInfo={false}
      strokeWidth={2}
      strokeColor={status !== 'error' ? 'var(--primary)' : ' var(--danger)'}
      className={`lm-c-loading-progress ${isHide ? 'lm-c-loading-progress-over' : ''}`}
    />
  )
}

ProgressComponent.defaultProps = {
  status: 'loading'
}

export default React.memo(ProgressComponent)
