import { useState, useEffect } from 'react'

import { PAGES } from 'config'
import { isMobileDevice } from 'config/userAgent'
import { getSportLexic } from 'helpers'
import { getMatchLastWatchSeconds, LastPlayPosition } from 'requests'

import { useMatchPopupStore } from 'features/MatchPopup/store'

import { SimplePlaylistButton } from '../SimplePlaylistButton'
import { List, Item } from './styled'

export const LiveMatchPlaylist = () => {
  const [lastPlayPosition, setLastPlayPosition] = useState<LastPlayPosition | null>(null)
  const { match } = useMatchPopupStore()

  useEffect(() => {
    if (match) {
      getMatchLastWatchSeconds(match?.sportType, match?.id)
        .then((lastPlayPositionSecond) => setLastPlayPosition(lastPlayPositionSecond))
    }
  }, [match])

  if (!match) return null

  const sport = getSportLexic(match.sportType)
  return (
    <List>
      <Item>
        <SimplePlaylistButton
          to={`/${sport}${PAGES.match}/${match.id}`}
          title={isMobileDevice ? 'watch' : 'watch_live_stream'}
        />
      </Item>
      <Item>
        <SimplePlaylistButton
          to={`/${sport}${PAGES.match}/${match.id}/?resume=${0}`}
          title='watch_from_beginning'
        />
      </Item>
      {lastPlayPosition?.second
        ? (
          <Item>
            <SimplePlaylistButton
              to={`/${sport}${PAGES.match}/${match.id}/?resume=${lastPlayPosition.second}`}
              title='watch_from'
              startWatch={lastPlayPosition?.second}
            />
          </Item>
        )
        : null}
    </List>
  )
}
