import {Fragment, type ReactNode} from 'react'
import {View} from 'react-native'

import {
  EmptyState,
  type EmptyStateAction,
} from '@/components/empty-state'
import {LoadingState} from '@/components/loading-state'
import {Divider} from '@/components/ui/divider'

type ListProps<T extends {id: string}> = {
  items: T[]
  renderItem: (item: T) => ReactNode
  emptyMessage: string
  emptyAction?: EmptyStateAction
  loading?: boolean
  loadingMore?: boolean
}

// shared list scaffold: loading/empty gates + divider-interleaved rows
export const List = <T extends {id: string}>({
  items,
  renderItem,
  emptyMessage,
  emptyAction,
  loading,
  loadingMore,
}: ListProps<T>) => {
  if (loading && items.length === 0) return <LoadingState />
  if (items.length === 0)
    return <EmptyState message={emptyMessage} action={emptyAction} />

  return (
    <View>
      {items.map((item, i) => (
        <Fragment key={item.id}>
          {i > 0 && <Divider />}
          {renderItem(item)}
        </Fragment>
      ))}
      {loadingMore && <LoadingState />}
    </View>
  )
}
