import {
  useCallback,
  useMemo,
  useState,
} from 'react'

import debounce from 'lodash/debounce'

import {
  Background,
  RewindIcon,
  Time,
} from './styled'

export type RewindProps = {
  isBackward?: boolean,
  isForward?: boolean,
  rewindCallback: () => void,
}

const RewindMobile = ({
  isBackward,
  isForward,
  rewindCallback,
}: RewindProps) => {
  const [isActive, setIsActive] = useState(false)
  const [time, setTime] = useState(0)

  const resetData = useCallback(() => {
    setIsActive(false)
    setTime(0)
  }, [])

  const resetDataDebounced = useMemo(() => (
    debounce(resetData, 1500)
  ), [resetData])

  const handleDoubleClick = useCallback(() => {
    setIsActive(true)
    rewindCallback()
    setTime(time + 10)
    resetDataDebounced()
  }, [resetDataDebounced, rewindCallback, time])

  const TimeContent = useMemo(() => (
    <Time
      isBackward={isBackward}
      isForward={isForward}
    >
      <span>{isBackward ? '-' : '+'}{time}</span>
      <RewindIcon src={`/images/rewind-${isBackward ? 'left' : 'right'}.svg`} />
    </Time>
  ), [isBackward, isForward, time])

  return (
    <Background
      isActive={isActive}
      isBackward={isBackward}
      isForward={isForward}
      onDoubleClick={handleDoubleClick}
    >
      {isActive && TimeContent}
    </Background>
  )
}

export default RewindMobile
