import type {
  FriendshipStatus,
  PublicProfile,
} from '@crumbs/core/schemas'
import {pluralize} from '@crumbs/core/text'
import {type ReactNode} from 'react'
import {View} from 'react-native'

import {Chip} from '@/components/chip'
import {Avatar} from '@/components/ui/avatar'
import {CardRow, CardRowTitle} from '@/components/ui/card'
import {Link} from '@/components/ui/link'
import {List} from '@/components/ui/list'
import {Text} from '@/components/ui/typography'
import {atoms as a, useTheme} from '@/sprinkles'

const STATUS_LABEL: Partial<Record<FriendshipStatus, string>> = {
  self: 'You',
  friends: 'Friends',
  pending_outgoing: 'Requested',
  pending_incoming: 'Wants to be friends',
}

// one profile row, reusable by any list container (List, VirtualList).
// accessory replaces the trailing friend count when a caller needs its own
// trailing content (e.g. a reactor's emoji)
export const UserRow = ({
  user,
  showStatus = true,
  accessory,
}: {
  user: PublicProfile
  showStatus?: boolean
  accessory?: (user: PublicProfile) => ReactNode
}) => {
  const t = useTheme()
  const statusLabel = showStatus
    ? STATUS_LABEL[user.friendshipStatus]
    : undefined
  return (
    <Link
      href={`/profile/${user.id}`}
      accessibilityLabel={`@${user.handle}`}
    >
      {(isPressed) => (
        <CardRow pressed={isPressed}>
          <View style={[a.flex_row, a.align_center, a.gap_sm]}>
            <Avatar
              handle={user.handle}
              uri={user.avatarUrl}
              size={36}
            />
            <CardRowTitle>@{user.handle}</CardRowTitle>
            {statusLabel && <Chip label={statusLabel} />}
          </View>
          {accessory ? (
            accessory(user)
          ) : (
            <Text style={[t.atoms.text_contrast_medium]}>
              {pluralize(user.friendCount, 'friend')}
            </Text>
          )}
        </CardRow>
      )}
    </Link>
  )
}

export const UserList = ({
  users,
  loading,
  loadingMore,
  emptyMessage = 'No people yet',
  showStatus = true,
  accessory,
}: {
  users: PublicProfile[]
  loading?: boolean
  loadingMore?: boolean
  emptyMessage?: string
  showStatus?: boolean
  accessory?: (user: PublicProfile) => ReactNode
}) => (
  <List
    items={users}
    loading={loading}
    loadingMore={loadingMore}
    emptyMessage={emptyMessage}
    renderItem={(user) => (
      <UserRow
        user={user}
        showStatus={showStatus}
        accessory={accessory}
      />
    )}
  />
)
