import React, { useContext } from 'react'
import { EntityStreamsGraphScreenContent } from '../components/EntityStreamsGraphScreenContent'
import { useNetwork } from '../components/useNetwork'
import { VideoImage } from '../components/VideoImage'
import { ScreenNames } from '../constants/ScreenNames'
import { ArtistContext } from '../contexts/ArtistContext'
import { UserContext } from '../contexts/UserContext'
import { EventType, sendAnalyticsEvent } from '../hooks/useAnalytics'
import { useVideoViews } from '../hooks/useVideoViews'
import { Strings } from '../i18n'
import { ReactNavigationProps } from '../Navigation'
import { Video } from '../types/types'

export interface VideoResponse {
  video: Video
}

export const VideoViewsGraphScreen: React.FC<
  ReactNavigationProps<ScreenNames.VideoViewsGraph>
> = ({ navigation, route }) => {
  const screenName = 'Video Views Graph Screen'
  const videoId = route.params.videoId
  const user = useContext(UserContext)
  const artist = useContext(ArtistContext)
  const countryCode = route.params.countryCode ?? 'worldwide'

  const { data, showToast, error, retry, refreshing } =
    useNetwork<VideoResponse>(
      `api/artists/${artist.sonyArtistId}/videos/${videoId}`,
      user,
      () =>
        sendAnalyticsEvent(EventType.PULL_TO_REFRESH, {
          artist_selected: artist.name,
          page: screenName,
          subject: 'user',
          verb: 'refreshed',
          object: 'video',
        })
    )
  const video = data?.video

  return video != null ? (
    <EntityStreamsGraphScreenContent
      screenTitle={video.videoTitle}
      title={Strings.Shared.ViewsWorldwide}
      headerImage={<VideoImage item={video} width={48} height={48} />}
      dsp={video.dsp}
      countryCode={countryCode}
      onPressMarketSelectorButton={() => {
        navigation.navigate('MarketSelector', {
          previousScreen: 'VideoViewsGraph',
        })
      }}
      onSelectTimeInterval={(selectedTimeInterval) => {
        sendAnalyticsEvent(EventType.GRAPH_TIMEFRAME_CHANGED, {
          artist_selected: artist.name,
          timeframe_selected: selectedTimeInterval,
          entity_id: videoId,
          screen_name: screenName,
          subject: 'user',
          verb: 'selected',
          object: 'graph_timeframe',
        })
      }}
      useEntityStreams={(interval: Interval) =>
        useVideoViews(videoId, interval, 'youtube', countryCode)
      }
      error={error}
      showToast={showToast}
      navigation={navigation}
      retry={retry}
      refreshing={refreshing}
    />
  ) : null
}
