import { secondsToHms } from 'helpers'

import { useSlider } from 'features/StreamPlayer/hooks/useSlider'
import { TimeTooltip } from 'features/StreamPlayer/components/TimeTooltip'

import {
  ProgressBarList,
  LoadedProgress,
  PlayedProgress,
  Scrubber,
} from './styled'

type Props = {
  duration: number,
  loadedProgress: number,
  onPlayedProgressChange: (progress: number) => void,
  playedProgress: number,
}

export const ProgressBar = ({
  duration,
  loadedProgress,
  onPlayedProgressChange,
  playedProgress,
}: Props) => {
  const progressBarRef = useSlider({ onChange: onPlayedProgressChange })
  const loadedFraction = Math.min(loadedProgress * 100 / duration, 100)
  const playedFraction = Math.min(playedProgress * 100 / duration, 100)

  return (
    <ProgressBarList ref={progressBarRef}>
      <LoadedProgress style={{ width: `${loadedFraction}%` }} />
      <PlayedProgress style={{ width: `${playedFraction}%` }} />
      <Scrubber style={{ left: `${playedFraction}%` }}>
        <TimeTooltip time={secondsToHms(playedProgress / 1000)} />
      </Scrubber>
    </ProgressBarList>
  )
}
