import React, { useContext, useState } from 'react'
import { SectionList, Text, View } from 'react-native'
import { dspTitleProps, sortCharts } from '../charts'
import { colorsV2 } from '../Colors'
import { ChartMarketPlacementRow } from '../components/ChartMarketPlacementRow'
import { CommonScreenContainer } from '../components/CommonScreenContainer'
import { ErrorBoundary } from '../components/ErrorBoundary'
import { GraphDetailScreenHeader } from '../components/GraphDetailScreenHeader'
import { HeaderNav } from '../components/HeaderNav'
import { MarketSelectorButton } from '../components/MarketSelectorButton'
import { ProductImage } from '../components/ProductImage'
import { SelectedMarketDivider } from '../components/SelectedMarketDivider'
import { ScreenNames } from '../constants/ScreenNames'
import { ArtistContext } from '../contexts/ArtistContext'
import { ScreenContext } from '../contexts/ScreenContext'
import { EventType, sendAnalyticsEvent } from '../hooks/useAnalytics'
import { useScreenRefreshControl } from '../hooks/useScreenRefreshControl'
import { useTrack } from '../hooks/useTrack'
import { useTrackCharts } from '../hooks/useTrackCharts'
import { useTrackTopCountryCodes } from '../hooks/useTrackTopCountries'
import { Strings } from '../i18n'
import { ReactNavigationProps } from '../Navigation'
import { TextStylesV2 } from '../Styles'
import { defaultTimeInterval } from '../types/TimeInterval'
import { notEmpty, timeRangeInterval } from '../util'

export const TrackChartsScreen: React.FC<
  ReactNavigationProps<ScreenNames.TrackCharts>
> = ({ navigation, route }) => {
  const screenName = 'Track Charts Screen'
  const { isrc, dsp } = route.params
  const artist = useContext(ArtistContext)
  const countryCode = route.params.countryCode ?? 'worldwide'

  const { data, retry, refreshing, showToast, error } = useTrack(isrc, () =>
    sendAnalyticsEvent(EventType.PULL_TO_REFRESH, {
      artist_selected: artist.name,
      page: screenName,
      subject: 'user',
      verb: 'refreshed',
      object: 'track',
    })
  )
  const track = data?.track
  const trackTopMarketCountryCodes = useTrackTopCountryCodes(isrc, 'last28days')

  const [scrollEnabled, setScrollEnabled] = useState<boolean>(true)

  const { refreshControl, screenContext } = useScreenRefreshControl(
    retry,
    refreshing
  )

  const interval = timeRangeInterval(defaultTimeInterval)

  const { data: chartsData } = useTrackCharts(isrc, interval, dsp)

  const chartsForDsp =
    chartsData?.charts
      ?.find((chart) => chart.dsp === dsp)
      ?.chartTrackPositions.sort(sortCharts) ?? []

  const selectedMarketChartPosition = chartsForDsp?.find(
    ({ chart }) => chart.countryCode === countryCode
  )

  const numTopChartMarkets = 5

  const top = [
    ...chartsForDsp.slice(0, numTopChartMarkets).map((chartTrackPosition) => ({
      ...chartTrackPosition,
      selected: false,
    })),
    selectedMarketChartPosition != null && countryCode != 'worldwide'
      ? { ...selectedMarketChartPosition, selected: true }
      : null,
  ].filter(notEmpty)
  const other = chartsForDsp
    .slice(numTopChartMarkets)
    .map((chartTrackPosition) => ({ ...chartTrackPosition, selected: false }))

  return (
    <ScreenContext.Provider value={screenContext}>
      <CommonScreenContainer>
        <HeaderNav
          title={track?.name}
          showToast={showToast}
          navigation={navigation}
          style={{
            zIndex: 10,
          }}
          right={
            <MarketSelectorButton
              countryCode={countryCode}
              onPress={() => {
                navigation.navigate('MarketSelector', {
                  previousScreen: 'TrackCharts',
                  topMarketCountryCodes: trackTopMarketCountryCodes,
                })
              }}
            />
          }
        />
        <ErrorBoundary error={error} refreshControl={refreshControl}>
          <View
            style={{
              flex: 1,
              paddingHorizontal: 8,
            }}
          >
            <GraphDetailScreenHeader
              image={
                track != null ? (
                  <ProductImage
                    product={track.product}
                    isExplicit={false}
                    size={48}
                  />
                ) : null
              }
              title={dspTitleProps[dsp].title}
              dsp={dsp}
            />
            {chartsForDsp != null && (
              <SectionList
                stickySectionHeadersEnabled={false}
                renderItem={({ item, index }) => (
                  <>
                    {item?.selected ? (
                      <SelectedMarketDivider style={{ paddingBottom: 16 }} />
                    ) : null}
                    <ChartMarketPlacementRow
                      countryCode={item.chart.countryCode}
                      countryName={
                        item.chart.countryName ?? item.chart.countryCode
                      }
                      current={item.current}
                      date={item.date ?? undefined}
                      style={{ marginBottom: 16 }}
                    />
                  </>
                )}
                renderSectionHeader={({ section: { title } }) => (
                  <Text
                    style={[
                      TextStylesV2.body,
                      { color: colorsV2.offWhite, marginVertical: 24 },
                    ]}
                  >
                    {title}
                  </Text>
                )}
                keyExtractor={(item, index) =>
                  item.chart.chartId + item.selected
                }
                sections={[
                  {
                    title: Strings.Shared.TopMarkets,
                    data: top,
                  },
                  other.length > 0
                    ? {
                        title: Strings.Shared.OtherMarkets,
                        data: other,
                      }
                    : null,
                ].filter(notEmpty)}
              />
            )}
          </View>
        </ErrorBoundary>
      </CommonScreenContainer>
    </ScreenContext.Provider>
  )
}
