import {
  useEffect,
  useState,
  RefObject,
} from 'react'

import { T9n } from 'features/T9n'
import { Icon } from 'features/Icon'
import { useAuthStore } from 'features/AuthStore'

import {
  AccessTimerContainer,
  PreviewInfo,
  SignInBtn,
  SignText,
  Timer,
  TimerContainer,
} from './styled'

import { SimplePopup } from '../SimplePopup'
import { secondsToHms } from '../../helpers'
import { getViewMatchDuration } from '../../requests/getViewMatchDuration'
import { usePageParams } from '../../hooks'
import { getUserInfo } from '../../requests'

type AccessTimerType = {
  access: boolean,
  isFullscreen: boolean,
  onFullscreenClick: () => void,
  playing: boolean,
  videoRef?: RefObject<HTMLVideoElement> | null,
}

const ACCESS_TIME = 60

export const AccessTimer = ({
  access,
  isFullscreen,
  onFullscreenClick,
  playing,
  videoRef,
}: AccessTimerType) => {
  const {
    logout,
    setUserInfo,
    userInfo,
  } = useAuthStore()

  const { profileId, sportType } = usePageParams()

  const [timeIsFinished, setTimeIsFinished] = useState(true)
  const [time, setTime] = useState(ACCESS_TIME)
  const isTimeExpired = time <= 0 || !access

  useEffect(() => {
    if (isTimeExpired) {
      document.pictureInPictureEnabled && document.exitPictureInPicture()
      setTimeIsFinished(true)
      videoRef?.current?.pause()
      setTime(0)
      if (isFullscreen) onFullscreenClick()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [access, playing, profileId])

  useEffect(() => {
    let stopWatch: ReturnType<typeof setInterval> | null = null
    if (playing) {
      stopWatch = setInterval(() => {
        setTime((prev) => prev - 1)
      }, 1000)
    } else {
      stopWatch && clearInterval(stopWatch)
    }
    return () => {
      stopWatch && clearInterval(stopWatch)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [playing, profileId])

  useEffect(() => {
    (async () => {
      setTime(ACCESS_TIME)
      const updatedUserInfo = await getUserInfo()
      setUserInfo(updatedUserInfo)
      const timeViewed = await getViewMatchDuration({
        matchId: profileId,
        sportType,
        userId: Number(updatedUserInfo?.email),
      })
      setTime(isTimeExpired ? 0 : (ACCESS_TIME - Number(timeViewed.duration)))
    })()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [profileId])

  return (
    <>
      {(!userInfo || Number(userInfo?.email) < 0) && access && time > 0
        ? (
          <AccessTimerContainer isFullscreen={isFullscreen}>
            <TimerContainer>
              <PreviewInfo>
                <Timer>{secondsToHms(time)}&nbsp;</Timer>
                <T9n t='game_preview' className='gamePreview' />
              </PreviewInfo>
              <SignText>
                <T9n t='sign_in_full_game' />
              </SignText>
            </TimerContainer>
            <SignInBtn onClick={() => logout('saveToken')}>
              <T9n t='sign_in' />
            </SignInBtn>
          </AccessTimerContainer>
        )
        : (
          <SimplePopup
            isModalOpen={timeIsFinished}
            withCloseButton={false}
            headerName='sec_60'
            mainText='continue_watching'
            buttonName='sign_in'
            onHandle={() => logout('saveToken')}
            icon={<Icon refIcon='ExclamationPoint' />}
          />
        )}
    </>
  )
}
