import { Interval } from 'date-fns'
import React from 'react'
import { StyleProp, View, ViewStyle, Text } from 'react-native'

import { colors } from '../Colors'
import { dspNames, StreamingDsp } from '../Consts'
import { TextStyles } from '../Styles'
import { useEntityStreamsSummary } from '../hooks/useEntityStreams'
import { useRegion } from '../hooks/useRegions'
import { useTrackCountryStreams } from '../hooks/useTrackCountryStreams'
import { useTrackTopCountries } from '../hooks/useTrackTopCountries'
import { localizedCountryName, Strings } from '../i18n'
import { TimeInterval } from '../types/TimeInterval'
import { formatCountShort, notEmpty, timeRangeInterval } from '../util'
import { formatInterval } from '../util/date'
import { AutoLayout } from './AutoLayout'
import { CountryIconAndName } from './CountryIconAndName'
import { DataTile, DataTileText } from './DataTile'
import { PercentPill } from './PercentPill'
import { SelectedMarketDivider } from './SelectedMarketDivider'

export const SimpleCountryRow: React.FC<{
  countryCode: string
  streamCount: number
  changePercentage: number | null /* null for e.g. infinite change, 0->N */
  style?: StyleProp<ViewStyle>
}> = (props) => {
  const region = useRegion(props.countryCode)

  const countryName = region
    ? localizedCountryName(region)
    : props.countryCode /* graceful fallback */

  return (
    <View
      key={props.countryCode}
      style={[
        {
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
        },
        props.style,
      ]}
    >
      <CountryIconAndName
        countryCode={props.countryCode}
        countryName={countryName}
        style={{ flexShrink: 1 }}
      />
      <View
        style={{
          flexBasis: 100,
          flexDirection: 'row',
          justifyContent: 'flex-end',
          alignItems: 'center',
        }}
      >
        <Text style={[TextStyles.tinyBold, { color: colors.white }]}>
          {formatCountShort(props.streamCount)}
        </Text>
        <PercentPill
          percentage={
            // In the case of infinity (null), we make the compromise of using
            // "0%" so that the UI doesn't jump around
            props.changePercentage ?? 0
          }
          size="small"
          style={{ width: 54, paddingHorizontal: 2, marginStart: 8 }}
        />
      </View>
    </View>
  )
}

const CountryRow: React.FC<{
  countryCode: string
  dsp: StreamingDsp | 'all'
  isrc: string
  currentInterval: Interval
  style?: StyleProp<ViewStyle>
}> = ({ countryCode, dsp, isrc, currentInterval, style }) => {
  const { data } = useEntityStreamsSummary(currentInterval, (interval) =>
    useTrackCountryStreams(isrc, interval, countryCode, dsp)
  )
  const summary = data

  return summary ? (
    <SimpleCountryRow
      countryCode={countryCode}
      style={style}
      streamCount={summary.currentIntervalStreamsSum}
      changePercentage={summary.changePercentage}
    />
  ) : null
}

/**
 * A tile representing the top countries (by streams) for a track and DSP
 */
export const TrackTopStreamingCountriesTile: React.FC<{
  isrc: string
  dsp: StreamingDsp | 'all'
  countryCode: string
  timeInterval: TimeInterval
  style?: StyleProp<ViewStyle>
}> = ({ isrc, dsp, countryCode, timeInterval, style }) => {
  const currentInterval = timeRangeInterval(timeInterval)

  const { data, error } = useTrackTopCountries(isrc, currentInterval, dsp)
  const countries = data?.countries
  const countriesForDsp = countries?.find((country) => country.dsp === dsp)
  const emptyText =
    dsp !== 'all'
      ? Strings.Shared.TrackNoTopCountriesForDsp.replace('%s', dspNames[dsp])
      : Strings.Shared.TrackNoTopCountriesForAllDsps

  return (
    <DataTile
      dsp={dsp}
      title={Strings.Shared.TopStreamingMarkets}
      subTitle={formatInterval(currentInterval)}
      style={[{ minHeight: 320 }, style]}
      error={error}
    >
      {countriesForDsp != null ? (
        countriesForDsp.streams.length > 0 ? (
          <AutoLayout gap={16}>
            {[
              ...countriesForDsp.streams.map((x) => (
                <CountryRow
                  key={x.item.countryCode}
                  countryCode={x.item.countryCode}
                  currentInterval={currentInterval}
                  isrc={isrc}
                  dsp={dsp}
                />
              )),
              ...(countryCode !== 'worldwide'
                ? [
                    <SelectedMarketDivider key="selectedMarket" />,
                    <CountryRow
                      key={`selected-${countryCode}`}
                      countryCode={countryCode}
                      currentInterval={currentInterval}
                      isrc={isrc}
                      dsp={dsp}
                    />,
                  ]
                : []),
            ].filter(notEmpty)}
          </AutoLayout>
        ) : (
          <DataTileText text={emptyText} />
        )
      ) : null}
    </DataTile>
  )
}
