import React from 'react'

import { StreamDemographicsDsp, streamDemographicsDsps } from '../Consts'
import { Carousel } from '../components/Carousel'
import { DspDemographicsFieldsFragment } from '../graphql/__generated__/sdk'
import { useArtistStreamsDemographics } from '../hooks/useArtistStreamsDemographics'
import { carouselStyleProps, styles } from '../screens/TrackScreenV2'
import { TimeInterval } from '../types/TimeInterval'
import { timeRangeInterval } from '../util'
import { DemographicsTile } from './DemographicsTile'

const ArtistStreamsDemographicsTile: React.FC<{
  dsp: StreamDemographicsDsp
  timeInterval: TimeInterval
  countryCode: string
}> = ({ dsp, timeInterval, countryCode }) => {
  const { demographics, error } = useArtistStreamsDemographics(
    timeRangeInterval(timeInterval),
    countryCode
  )

  const demographicsForDsp: DspDemographicsFieldsFragment | undefined =
    demographics?.find((x) => x.dsp.id === dsp)

  return (
    <DemographicsTile
      key={dsp}
      dsp={dsp}
      demographics={demographicsForDsp}
      error={error}
      timeInterval={timeInterval}
      style={styles.tile}
    />
  )
}

export const ArtistStreamsDemographicsCarousel: React.FC<{
  timeInterval: TimeInterval
  countryCode: string
  onSwipe: (item: StreamDemographicsDsp) => void
}> = ({ timeInterval, countryCode, onSwipe }) => {
  return (
    <Carousel<StreamDemographicsDsp>
      items={[...streamDemographicsDsps]}
      renderItem={({ item }) => (
        <ArtistStreamsDemographicsTile
          key={item}
          dsp={item}
          timeInterval={timeInterval}
          countryCode={countryCode}
        />
      )}
      onSwipe={onSwipe}
      {...carouselStyleProps}
    />
  )
}
