/* eslint-disable  @typescript-eslint/no-explicit-any */
import { useEffect } from 'react'

import includes from 'lodash/includes'

import { usePageParams } from 'hooks/usePageParams'

import { API_ROOT } from 'config'

import { readToken } from 'helpers'

import { AirplayButton, AirplayIcon } from './styled'

type Props = {
  videoRef: React.RefObject<HTMLVideoElement>,
}

export const AirPlay = ({ videoRef }: Props) => {
  const { profileId: matchId, sportType } = usePageParams()

  useEffect(() => {
    const baseUrl = includes(videoRef?.current?.src, '.m3u8')
      ? `${API_ROOT}/video/chromecast/stream/${sportType}/${matchId}.m3u8?access_token=${readToken()}`
      : videoRef?.current?.src!

    const video = videoRef.current!
    const airPlayBtn = document.getElementById('airPlay')!

    const changeAvailability = (event: any) => {
      switch (event.availability) {
        case 'available':
          airPlayBtn.style.display = 'block'
          break
        case 'unavailable':
          airPlayBtn.style.display = 'none'
          break
      }
    }

    const onAirplayClick = () => {
      video.src = baseUrl
      video.load();

      (video as any).webkitShowPlaybackTargetPicker()
    }

    if ((window as any).WebKitPlaybackTargetAvailabilityEvent && video) {
      video.addEventListener('webkitplaybacktargetavailabilitychanged', changeAvailability)
      airPlayBtn.addEventListener('click', onAirplayClick)
    }

    return () => {
      video.removeEventListener('webkitplaybacktargetavailabilitychanged', changeAvailability)
      airPlayBtn.removeEventListener('click', onAirplayClick)
    }
  }, [matchId, sportType, videoRef])

  return (
    <AirplayButton id='airPlay'>
      <AirplayIcon src='/images/airplay.svg' />
    </AirplayButton>
  )
}
