import GradientFlatList from '@app/components/GradientFlatList'
import ListItem from '@app/components/ListItem'
import { Artist } from '@app/models/music'
import { artistsAtom, artistsUpdatingAtom, useUpdateArtists } from '@app/state/music'
import { useNavigation } from '@react-navigation/native'
import { useAtomValue } from 'jotai/utils'
import React, { useEffect } from 'react'
import { StyleSheet } from 'react-native'

const ArtistItem = React.memo<{ item: Artist }>(({ item }) => {
  const navigation = useNavigation()

  return (
    <ListItem
      item={item}
      showArt={true}
      showStar={false}
      listStyle="big"
      onPress={() => navigation.navigate('ArtistView', { id: item.id, title: item.name })}
    />
  )
})

const ArtistRenderItem: React.FC<{ item: Artist }> = ({ item }) => <ArtistItem item={item} />

const ArtistsList = () => {
  const artists = useAtomValue(artistsAtom)
  const updating = useAtomValue(artistsUpdatingAtom)
  const updateArtists = useUpdateArtists()

  useEffect(() => {
    if (artists.length === 0) {
      updateArtists()
    }
  })

  return (
    <GradientFlatList
      contentContainerStyle={styles.listContent}
      data={artists}
      renderItem={ArtistRenderItem}
      keyExtractor={item => item.id}
      onRefresh={updateArtists}
      refreshing={updating}
      overScrollMode="never"
    />
  )
}

const styles = StyleSheet.create({
  listContent: {
    minHeight: '100%',
    paddingHorizontal: 10,
    paddingTop: 6,
  },
})

export default ArtistsList
