import React from 'react'
import { View, FlatList, RefreshControlProps } from 'react-native'

import { CountrySkeleton } from '../components/Skeleton'
import { CountryWithStreams, Country } from '../types/Country'
import { formatCountryName } from '../util'
import { CountryStreamsListItem } from './listitems/CountryStreamsListItem'

type CountryWithStreamsAndPosition = CountryWithStreams & { position: number }
interface Props {
  countries?: CountryWithStreamsAndPosition[]
  onPressCountry: (country: Country) => void
  refreshControl?: React.ReactElement<RefreshControlProps>
}

export function Countries(props: Props): React.ReactElement {
  const maxStreams = (countries: CountryWithStreamsAndPosition[]) =>
    Math.max(...countries.map((country) => country.data.current))
  return props.countries ? (
    <View style={{ paddingVertical: 8, flex: 1 }}>
      <FlatList
        keyboardDismissMode="on-drag"
        data={props.countries}
        renderItem={renderCountry(
          props.onPressCountry,
          maxStreams(props.countries)
        )}
        keyExtractor={keyForCountry}
        refreshControl={props.refreshControl}
      />
    </View>
  ) : (
    <CountrySkeleton />
  )
}

function renderCountry(
  onPress: (country: Country) => void,
  maxStreams: number
): (item: { item: CountryWithStreamsAndPosition }) => React.ReactElement {
  return ({ item }) => {
    const country = item.item
    const streams = item.data
    const props = {
      index: item.position,
      item: {
        name: formatCountryName(country.name),
        streams,
        maxStreams,
        selected: true,
      },
    }
    return (
      <CountryStreamsListItem {...props} onPress={() => onPress(country)} />
    )
  }
}

function keyForCountry(country: CountryWithStreamsAndPosition) {
  return country.item.countryCode
}
