import React, { useContext } from 'react'

import { ReactNavigationProps } from '../Navigation'
import { EntityStreamsSourceScreenContent } from '../components/EntityStreamsSourceScreenContent'
import { VideoImage } from '../components/VideoImage'
import { ScreenNames } from '../constants/ScreenNames'
import { ArtistContext } from '../contexts/ArtistContext'
import { EventType, sendAnalyticsEvent } from '../hooks/useAnalytics'
import { useScreenTimeInterval } from '../hooks/useScreenTimeInterval'
import { useVideo } from '../hooks/useVideo'
import { useVideoViewSources } from '../hooks/useVideoViewSources'
import { defaultTimeInterval } from '../types/TimeInterval'
import { timeRangeInterval } from '../util'

export const VideoViewSourcesScreen: React.FC<
  ReactNavigationProps<ScreenNames.VideoViewSources>
> = ({ navigation, route }) => {
  const screenName = 'Video View Sources Screen'
  const { video_id: videoId, dsp } = route.params

  const artist = useContext(ArtistContext)
  const countryCode = route.params.market ?? 'worldwide'
  const videoResponse = useVideo(videoId)

  const onPullToRefresh = () => {
    sendAnalyticsEvent(EventType.PULL_TO_REFRESH, {
      artist_selected: artist.name,
      page: screenName,
      subject: 'user',
      verb: 'refreshed',
      object: 'video',
    })
    videoResponse.retry()
  }
  const video = videoResponse.data?.artist?.video

  const [selectedTimeInterval, setSelectTimeInterval] = useScreenTimeInterval(
    defaultTimeInterval,
    {
      screenName,
      artistName: artist.name,
      entityId: artist.sonyArtistId,
    }
  )

  const { sources } = useVideoViewSources(
    videoId,
    timeRangeInterval(selectedTimeInterval),
    dsp,
    countryCode
  )

  return (
    <EntityStreamsSourceScreenContent
      screenName={screenName}
      screenTitle={video?.title}
      headerImage={
        video != null ? (
          <VideoImage item={video} width={48} height={48} />
        ) : null
      }
      dsp={dsp}
      countryCode={countryCode}
      sources={sources}
      selectedTimeInterval={selectedTimeInterval}
      onTimeIntervalChange={setSelectTimeInterval}
      error={videoResponse.error}
      showToast={videoResponse.showToast}
      navigation={navigation}
      retry={onPullToRefresh}
      refreshing={videoResponse.refreshing}
      onPressMarketSelectorButton={() => {
        navigation.navigate('MarketSelector', {
          previousScreen: 'VideoViewSources',
        })
      }}
    />
  )
}
