import React, { useContext } from 'react'
import { View } from 'react-native'
import { FlatList } from 'react-native-gesture-handler'

import { ReactNavigationProps } from '../Navigation'
import { dspTitleProps } from '../charts'
import { ArtistImage } from '../components/ArtistImage'
import { CommonScreenContainer } from '../components/CommonScreenContainer'
import { ErrorBoundary } from '../components/ErrorBoundary'
import { GraphDetailScreenHeader } from '../components/GraphDetailScreenHeader'
import { HeaderNav } from '../components/HeaderNav'
import {
  MarketChartTrackPositionItem,
  MarketChartTrackPositionsEmpty,
} from '../components/MarketChartTrackPositionsTile'
import { MarketSelectorButton } from '../components/MarketSelectorButton'
import { ScreenNames } from '../constants/ScreenNames'
import { ArtistContext } from '../contexts/ArtistContext'
import { EventType, sendAnalyticsEvent } from '../hooks/useAnalytics'
import { useMarketChartTrackPositions } from '../hooks/useMarketChartTrackPositions'
import { useScreenRefreshControl } from '../hooks/useScreenRefreshControl'
import { Strings } from '../i18n'
import { defaultTimeInterval } from '../types/TimeInterval'
import { ChartTrackPosition } from '../types/types'
import { timeRangeInterval } from '../util'

export const MarketChartsScreen: React.FC<
  ReactNavigationProps<ScreenNames.MarketCharts>
> = ({ navigation, route }) => {
  const screenName = 'Market Charts Screen'
  const { market, dsp } = route.params
  const artist = useContext(ArtistContext)
  const interval = timeRangeInterval(defaultTimeInterval)
  const chartGroup = dspTitleProps[dsp]
  const { data, error, retry, refreshing } = useMarketChartTrackPositions(
    chartGroup.chartGroup,
    market,
    interval
  )
  const onPullToRefresh = () => {
    sendAnalyticsEvent(EventType.PULL_TO_REFRESH, {
      artist_selected: artist.name,
      page: screenName,
      subject: 'user',
      verb: 'refreshed',
      object: 'track',
    })
    retry()
  }
  const { refreshControl } = useScreenRefreshControl(
    onPullToRefresh,
    refreshing
  )

  const chartTrackPositions = data?.chartTrackPositions

  return (
    <CommonScreenContainer screenName={screenName}>
      <HeaderNav
        title={artist.name}
        showToast={false}
        navigation={navigation}
        style={{
          zIndex: 10,
        }}
        right={
          <MarketSelectorButton
            countryCode={market}
            onPress={() => {
              navigation.navigate('MarketSelector', {
                previousScreen: 'MarketCharts',
              })
            }}
          />
        }
      />
      <ErrorBoundary error={error} refreshControl={refreshControl}>
        <View
          style={{
            flex: 1,
            paddingHorizontal: 8,
          }}
        >
          <GraphDetailScreenHeader
            image={<ArtistImage artist={artist} size={48} />}
            title={dspTitleProps[dsp].title}
            dsp={dsp}
            dspAdditionalText={Strings.Shared.Chart}
          />
          {chartTrackPositions != null && (
            <FlatList
              data={chartTrackPositions}
              renderItem={({
                item,
              }: {
                item: ChartTrackPosition
                index: number
              }) => (
                <MarketChartTrackPositionItem
                  key={item.isrc}
                  chartTrackPosition={item}
                  style={{ paddingBottom: 16 }}
                  onPress={() => {
                    navigation.navigate('Track', {
                      isrc: item.isrc,
                      market,
                    })
                  }}
                />
              )}
              ListEmptyComponent={MarketChartTrackPositionsEmpty}
              keyExtractor={(item) => item.isrc}
              refreshControl={refreshControl}
            />
          )}
        </View>
      </ErrorBoundary>
    </CommonScreenContainer>
  )
}
