import React, { useContext } from 'react'
import { ActivityIndicator, View } from 'react-native'

import { ReactNavigationProps } from '../Navigation'
import { CommonScreenContainer } from '../components/CommonScreenContainer'
import { ErrorBoundary } from '../components/ErrorBoundary'
import { GraphDetailScreenHeader } from '../components/GraphDetailScreenHeader'
import { HeaderNav } from '../components/HeaderNav'
import { ProductImage } from '../components/ProductImage'
import { TimeIntervalSelector } from '../components/TimeIntervalSelector'
import { TrackComparison } from '../components/TrackComparison'
import { ScreenNames } from '../constants/ScreenNames'
import { ArtistContext } from '../contexts/ArtistContext'
import { EventType, sendAnalyticsEvent } from '../hooks/useAnalytics'
import { useProduct } from '../hooks/useProducts'
import { useScreenRefreshControl } from '../hooks/useScreenRefreshControl'
import { useScreenTimeInterval } from '../hooks/useScreenTimeInterval'
import { Strings } from '../i18n'
import { getTracksWithAllDsp } from '../streams'
import { defaultTimeInterval } from '../types/TimeInterval'
import { productImageFieldsFromProduct } from '../types/graphqlCompatibilityHelpers'
import { isProductExplicit, timeRangeInterval } from '../util'
import { formatInterval } from '../util/date'

export const ProductTracksComparisonScreen: React.FC<
  ReactNavigationProps<ScreenNames.ProductTracksComparison>
> = ({ navigation, route }) => {
  const screenName = 'Product Tracks Comparison Screen'
  const artist = useContext(ArtistContext)

  const productId = route.params.product_id
  const dsp = 'all'

  const maxInterval = defaultTimeInterval //Longest interval represented in the graph

  const [selectedTimeInterval, selectTimeInterval] = useScreenTimeInterval(
    maxInterval,
    {
      screenName,
      artistName: artist.name,
      entityId: productId,
    }
  )

  const interval = timeRangeInterval(selectedTimeInterval)

  const { error, data, showToast, retry, refreshing } = useProduct(
    productId,
    interval
  )

  const onPullToRefresh = () => {
    sendAnalyticsEvent(EventType.PULL_TO_REFRESH, {
      artist_selected: artist.name,
      timeframe_selected: selectedTimeInterval,
      page: screenName,
      subject: 'user',
      verb: 'refreshed',
      object: 'product',
    })
    retry()
  }
  const { refreshControl } = useScreenRefreshControl(
    onPullToRefresh,
    refreshing
  )

  const product = data?.product
  const tracks =
    data?.streams != null ? getTracksWithAllDsp(data.streams) : null

  return (
    <CommonScreenContainer screenName={screenName}>
      <ErrorBoundary error={error} refreshControl={refreshControl}>
        <HeaderNav
          title={data?.product?.name ?? ' '}
          titleSecondary={data?.product?.digitalTitleSuppl ?? ' '}
          showToast={showToast}
          navigation={navigation}
          style={{
            zIndex: 10,
          }}
        />
        <View
          style={{
            paddingHorizontal: 10,
            flex: 1,
            justifyContent: 'space-between',
          }}
        >
          <GraphDetailScreenHeader
            image={
              product && (
                <ProductImage
                  size={48}
                  product={productImageFieldsFromProduct(product)}
                  isExplicit={isProductExplicit(product)}
                />
              )
            }
            dsp={dsp}
            title={Strings.Shared.TrackPerformance}
            subTitle={formatInterval(interval)}
          />
          {tracks != null ? (
            <TrackComparison tracks={tracks} />
          ) : (
            <ActivityIndicator />
          )}
          <TimeIntervalSelector
            selectedTimeInterval={selectedTimeInterval}
            onSelectTimeInterval={selectTimeInterval}
          />
        </View>
      </ErrorBoundary>
    </CommonScreenContainer>
  )
}
