import React from 'react'
import { SectionList } from 'react-native'
import { Strings } from '../i18n'
import { VideoListItem } from '../screens/VideosScreen'
import { Product } from '../types/Product'
import { Track } from '../types/Track'
import { Video } from '../types/types'
import { ProductListItem } from './ProductListItem'
import { SectionTitle } from './SectionTitle'
import { TrackListSkeleton } from './Skeleton'
import { StreamsListItem } from './StreamsListItem'

export type EntityType = 'track' | 'video' | 'product'

export type Entity =
  | {
      entityType: 'track'
      track: Track
    }
  | {
      entityType: 'video'
      video: Video
    }
  | {
      entityType: 'product'
      product: Product
    }

const sectionTitles: Record<EntityType, string> = {
  track: Strings.Shared.Tracks,
  video: Strings.Shared.Videos,
  product: Strings.ProductScreen.AlbumsEPsAndLPs,
}

/**
 * List of different types of entities, grouped into sections by type
 */
export const EntityList: React.FC<{
  items: Record<EntityType, Entity[]>
  onPressItem: (item: Entity) => void
}> = ({ items, onPressItem }) => {
  const sections = Object.entries(items).flatMap(([itemType, data]) =>
    data.length > 0
      ? {
          data,
          key: itemType as EntityType,
        }
      : ([] as { data: Entity[]; key: EntityType }[])
  )

  return items ? (
    <SectionList
      sections={sections}
      renderItem={({ item, index }) => {
        if (item.entityType === 'track') {
          return (
            <StreamsListItem
              track={item.track}
              onPress={() => onPressItem(item)}
            />
          )
        }
        if (item.entityType === 'video') {
          return (
            <VideoListItem
              item={item.video}
              onPress={() => onPressItem(item)}
            />
          )
        }
        if (item.entityType === 'product') {
          return (
            <ProductListItem
              product={item.product}
              onPress={() => onPressItem(item)}
            />
          )
        }
      }}
      keyExtractor={(item) => {
        if (item.entityType === 'track') {
          return item.track.sonyTrackId
        }
        if (item.entityType === 'video') {
          return item.video.videoId
        }
        if (item.entityType === 'product') {
          return item.product.productId
        }
      }}
      renderSectionHeader={({ section }) => (
        <SectionTitle title={sectionTitles[section.key]} />
      )}
      stickySectionHeadersEnabled={false}
    />
  ) : (
    <TrackListSkeleton numItems={6} />
  )
}
