import React, { useState } from 'react'
import { SectionList, Text, TouchableOpacity, View } from 'react-native'
import { colorsV2 } from '../Colors'
import { CommonScreenContainer } from '../components/CommonScreenContainer'
import { CountryRow } from '../components/CountryRow'
import { ErrorBoundary } from '../components/ErrorBoundary'
import { HeaderNav } from '../components/HeaderNav'
import { SearchBar } from '../components/SearchBar'
import { ScreenNames } from '../constants/ScreenNames'
import { useRegions } from '../hooks/useRegions'
import { localizedCountryName, Strings } from '../i18n'
import { ReactNavigationProps } from '../Navigation'
import { TextStylesV2 } from '../Styles'
import { normalizeNameForSearch, notEmpty } from '../util'

export const MarketSelectorScreen: React.FC<
  ReactNavigationProps<ScreenNames.MarketSelector>
> = ({ navigation, route }) => {
  const screenName = 'Market Selector Screen'
  //const { isrc, dsp } = route.params

  const { data, error, refreshControl } = useRegions()
  const regions = data?.regions
  const topMarketCountryCodes = route.params.topMarketCountryCodes ?? []
  const [searchFilter, setSearchFilter] = useState('')
  const countries =
    regions != null
      ? regions
          .filter(({ countryCode }) => countryCode !== 'unknown')
          .filter(({ countryName }) =>
            normalizeNameForSearch(countryName).includes(
              normalizeNameForSearch(searchFilter)
            )
          )
      : []
  const worldwide = countries.filter(
    ({ countryCode }) => countryCode === 'worldwide'
  )
  const countriesWithoutWorldwide = countries.filter(
    ({ countryCode }) => countryCode !== 'worldwide'
  )

  const topMarkets = topMarketCountryCodes.flatMap((countryCode) => {
    const region = countriesWithoutWorldwide.find(
      (c) => c.countryCode === countryCode
    )
    return region ? [region] : []
  })

  const otherMarkets = countriesWithoutWorldwide.filter(
    ({ countryCode }) => !topMarketCountryCodes.includes(countryCode)
  )

  return (
    <CommonScreenContainer>
      <HeaderNav
        title={Strings.Shared.ChooseMarket}
        showToast={false}
        navigation={navigation}
        style={{
          zIndex: 10,
        }}
      />
      <ErrorBoundary error={error} refreshControl={refreshControl}>
        <View style={{ paddingHorizontal: 16, marginBottom: 20 }}>
          <SearchBar
            filter={searchFilter}
            setFilter={setSearchFilter}
            placeholder={Strings.Shared.SearchHintMarket}
          />
        </View>

        <SectionList
          stickySectionHeadersEnabled={false}
          renderItem={({ item, index }) => (
            <TouchableOpacity
              onPress={() => {
                navigation.navigate(route.params.previousScreen, {
                  countryCode: item.countryCode,
                })
              }}
              key={item.countryCode}
            >
              <CountryRow
                key={index}
                countryCode={item.countryCode}
                countryName={localizedCountryName(item)}
                style={{ marginVertical: 16 }}
              />
            </TouchableOpacity>
          )}
          renderSectionHeader={({ section: { title } }) =>
            title != null ? (
              <Text
                style={[
                  TextStylesV2.body,
                  { color: colorsV2.offWhite, marginVertical: 24 },
                ]}
              >
                {title}
              </Text>
            ) : null
          }
          keyExtractor={(item, index) => item.countryCode}
          sections={[
            {
              data: worldwide,
            },
            topMarkets.length > 0
              ? {
                  title: Strings.Shared.TopStreamingMarkets,
                  data: topMarkets,
                }
              : null,
            otherMarkets.length > 0
              ? {
                  title: Strings.Shared.OtherMarkets,
                  data: otherMarkets,
                }
              : null,
          ].filter(notEmpty)}
          style={{ paddingHorizontal: 16 }}
          refreshControl={refreshControl}
        />
      </ErrorBoundary>
    </CommonScreenContainer>
  )
}
