import {pluralize} from '@crumbs/core/text'
import {View} from 'react-native'

import {AvatarStack} from '@/components/avatar-stack'
import {SyncBadge} from '@/components/sync-badge'
import {CardRow, CardRowTitle} from '@/components/ui/card'
import {Link} from '@/components/ui/link'
import {List} from '@/components/ui/list'
import {Thumbnail} from '@/components/ui/thumbnail'
import {Text} from '@/components/ui/typography'
import {atoms as a, useTheme} from '@/sprinkles'
import {type Trail} from '@/stores/trails'

// one trail row, reusable by any list container (List, VirtualList)
export const TrailRow = ({
  trail,
  currentUserId,
  hideAuthor,
}: {
  trail: Trail
  currentUserId?: string
  // suppress "Shared by @handle" entirely, for single-subject lists
  // (e.g. a profile's activity) where the author is already implied
  hideAuthor?: boolean
}) => {
  const t = useTheme()
  return (
    <Link href={`/trail/${trail.id}`} accessibilityLabel={trail.name}>
      {(isPressed) => (
        <CardRow
          pressed={isPressed}
          leading={
            <Thumbnail
              uri={trail.coverImageUrl}
              width={52}
              height={52}
              accessibilityLabel={`${trail.name} cover`}
            />
          }
        >
          <View
            style={[
              a.flex_row,
              a.align_center,
              a.justify_between,
              a.gap_sm,
            ]}
          >
            <CardRowTitle>
              {trail.pinned ? `📌 ${trail.name}` : trail.name}
            </CardRowTitle>
            <AvatarStack members={trail.members} />
          </View>
          <Text style={t.atoms.text_contrast_medium}>
            {pluralize(trail.crumbCount, 'crumb')}
            {trail.unseenCount > 0 && ` · ${trail.unseenCount} new`}
            {!hideAuthor &&
              currentUserId !== undefined &&
              trail.authorId !== currentUserId &&
              ` · Shared by @${trail.authorHandle}`}
          </Text>
          <SyncBadge scope={trail.id} />
        </CardRow>
      )}
    </Link>
  )
}

export const TrailList = ({
  trails,
  loading,
  loadingMore,
  emptyMessage = 'No trails yet',
  currentUserId,
}: {
  trails: Trail[]
  loading?: boolean
  loadingMore?: boolean
  emptyMessage?: string
  currentUserId?: string
}) => (
  <List
    items={trails}
    loading={loading}
    loadingMore={loadingMore}
    emptyMessage={emptyMessage}
    renderItem={(trail) => (
      <TrailRow trail={trail} currentUserId={currentUserId} />
    )}
  />
)
