import { useMemo, RefObject } from 'react'

import { secondsToHms } from 'helpers'

import type { Chapters } from '../../../StreamPlayer/types'
import { calculateChapterStyles } from './helpers/calculateChapterStyles'

export type Props = {
  activeChapterIndex: number,
  allPlayedProgress: number,
  chapters: Chapters,
  duration: number,
  isScrubberVisible?: boolean,
  loadedProgress: number,
  onPlayedProgressChange: (progress: number, seeking: boolean) => void,
  onTouchEnd?: () => any,
  onTouchStart?: () => any,
  playedProgress: number,
  videoRef?: RefObject<HTMLVideoElement>,
}

export const useProgressBar = ({
  activeChapterIndex,
  allPlayedProgress,
  chapters = [],
  duration,
  loadedProgress,
  playedProgress,
}: Props) => {
  const calculatedChapters = useMemo(
    () => calculateChapterStyles({
      activeChapterIndex,
      chapters,
      loadedProgress,
      playedProgress,
      videoDuration: duration,
    }),
    [
      activeChapterIndex,
      loadedProgress,
      playedProgress,
      duration,
      chapters,
    ],
  )

  return {
    calculatedChapters,
    playedProgressInPercent: Math.min(allPlayedProgress * 100 / duration, 100),
    time: secondsToHms(allPlayedProgress / 1000),
  }
}
