import React from 'react'

import { useSelector, useDispatch } from 'react-redux'
import {
  hasNextSegment,
  selectRunning,
  selectInterval
} from '../store/selectors'
import { incrementSegment, stop, pause, start } from '../store/actions'
import { FiPlay, FiPause, FiSquare } from 'react-icons/fi'
import { useInterval } from './generics/useInterval'
import { IconButton } from '../styles/IconButton'

export const PlayerControl = () => {
  const dispatch = useDispatch()
  const running = useSelector(selectRunning)
  const hasNext = useSelector(hasNextSegment)
  const interval = useSelector(selectInterval)

  useInterval(
    () => {
      if (!hasNext) dispatch(pause())
      else dispatch(incrementSegment())
    },
    running ? interval : null
  )

  return (
    <>
      <IconButton Icon={FiSquare} onClick={() => dispatch(stop())} />
      <IconButton
        Icon={running ? FiPause : FiPlay}
        onClick={() => dispatch(running ? pause() : start())}
        disabled={!hasNext}
      />
    </>
  )
}
