import React, { useEffect, useState } from 'react'

import { Box } from '../box'
import { styled, useStyleConfig, vui } from '../core'
import { cs } from '../utils'
import { ProgressProps } from './progress.types'

export const ProgressBase = styled.divBox`
  display: flex;
  width: 100%;
`

const minPercentageDisplay = 3
const maxValue = 100

/** Indicates a process progress. */
export const Progress = vui<'div', ProgressProps>((props, ref) => {
  const { className, value = 0, showPercentage, ...rest } = props

  const [width, setWidth] = useState(0)

  const styles = useStyleConfig('Progress', props)

  useEffect(() => {
    const w = !value ? 0 : Math.ceil(value)
    setWidth(w > maxValue ? maxValue : w)
  }, [value])

  const bg = rest.bg || styles.bg
  const color = rest.color || styles.color

  return (
    <ProgressBase
      className={cs('vui-progress', className)}
      ref={ref}
      {...styles.container}
      {...rest}
      bg={bg}
      borderRadius="sm"
      h={1}
    >
      <Box
        bg={color}
        borderRadius="sm"
        position="relative"
        textAlign="right"
        transition="width 0.4s ease-in-out;"
        w={`${width}%`}
      >
        {showPercentage && value >= minPercentageDisplay && (
          <Box {...styles.percentage} position="absolute" right="0">{`${width}%`}</Box>
        )}
      </Box>
    </ProgressBase>
  )
})

Progress.displayName = 'Progress'
export default Progress
