import React from 'react'
import {
  FlatList,
  Text,
  StyleSheet,
  StyleProp,
  ViewStyle,
  RefreshControlProps,
} from 'react-native'

import { colors } from '../Colors'
import { TextStyles } from '../Styles'
import { Strings } from '../i18n'
import { Track } from '../types/Track'
import { formatTrackName } from '../util'

export interface TrackListItem {
  track: Track
  currentPeriodStreams?: number
  changePercentage?: number
}

interface Props {
  tracks: TrackListItem[]
  filters?: React.ReactElement
  renderTrack: (track: TrackListItem, i: number) => React.ReactElement
  refreshControl?: React.ReactElement<RefreshControlProps>
  style?: StyleProp<ViewStyle>
}

const styles = StyleSheet.create({
  container: {},
  text: {
    ...TextStyles.body,
    color: colors.metals.metal0,
    padding: 12,
    textAlign: 'center',
  },
})

export function TrackList(props: Props) {
  return (
    <FlatList
      ListEmptyComponent={
        <Text style={styles.text}>{Strings.Shared.NoResults}</Text>
      }
      ListHeaderComponent={props.filters}
      data={props.tracks}
      style={[{ flex: 1 }, props.style]}
      contentContainerStyle={{ flexGrow: 1 }}
      keyExtractor={(track) => track.track.isrc}
      renderItem={({ item, index }) => props.renderTrack(item, index)}
      refreshControl={props.refreshControl}
    />
  )
}

export function sortByReleaseDate(a: TrackListItem, b: TrackListItem): number {
  return (
    // Treat missing dates as if it was old data when sorting
    new Date(b.track.product.releaseDate ?? 0).getTime() -
    new Date(a.track.product.releaseDate ?? 0).getTime()
  )
}

export function sortByStreams(a: TrackListItem, b: TrackListItem): number {
  return (b.currentPeriodStreams ?? 0) - (a.currentPeriodStreams ?? 0)
}

export function sortByChangePercentage(
  a: TrackListItem,
  b: TrackListItem
): number {
  return (b.changePercentage ?? 0) - (a.changePercentage ?? 0)
}

export function sortByName(a: TrackListItem, b: TrackListItem): number {
  return formatTrackName(a.track).localeCompare(formatTrackName(b.track))
}
