import React, { useState } from 'react'
import { Icon } from 'antd'
import classNames from 'classnames'
import './scrollIndicator.less'

function ScrollIndicator (props) {
  const [visible, setVisible] = useState(false)

  const checkScroll = () => {
    if (props.scrollRef) {
      return props.scrollRef.getScrollWidth() > props.scrollRef.getClientWidth()
    }
    return false
  }

  const handleWheel = ({ deltaY }) => {
    handleScroll(deltaY > 0 ? 'right' : 'left', 32)
  }

  const handleScroll = (type, step) => {
    step = step || props.step || 20
    if (checkScroll()) {
      const scrollWidth = props.scrollRef.getScrollWidth() - props.scrollRef.getClientWidth()
      const currLeft = props.scrollRef.getScrollLeft()
      const scrollLeft = currLeft - step
      const scrollRight = currLeft + step
      if (type === 'left') {
        props.scrollRef.scrollLeft(scrollLeft < 0 ? 0 : scrollLeft)
      } else {
        props.scrollRef.scrollLeft(scrollRight > scrollWidth ? scrollWidth : scrollRight)
      }
    }
  }

  return (
    <div
      onMouseEnter={() => { checkScroll() ? setVisible(true) : setVisible(false) }}
      onMouseLeave={() => { setVisible(false) }}
      onWheel={handleWheel}
      className='opt-scrollbar'
    >
      {props.children}
      <div onClick={() => handleScroll('left')} className={classNames('opt-scrollbar__prev', { visible })}>
        <Icon type='arrow-left' />
      </div>
      <div onClick={() => handleScroll('right')} className={classNames('opt-scrollbar__next', { visible })}>
        <Icon type='arrow-right' />
      </div>
    </div>
  )
}

export default ScrollIndicator