import type {DmConversation} from '@crumbs/core/schemas'
import {View} from 'react-native'

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 {formatShortDate} from '@/lib/dates'
import {atoms as a, useTheme} from '@/sprinkles'

// one inbox row, reusable by any list container
export const ConversationRow = ({
  conversation,
}: {
  conversation: DmConversation
}) => {
  const t = useTheme()
  const {peer, lastMessage, unreadCount} = conversation
  return (
    <Link
      href={`/dms/${conversation.id}`}
      accessibilityLabel={`Conversation with @${peer.handle}`}
    >
      {(isPressed) => (
        <CardRow
          pressed={isPressed}
          leading={
            <Avatar
              handle={peer.handle}
              uri={peer.avatarUrl}
              size={36}
            />
          }
        >
          <View
            style={[
              a.flex_row,
              a.align_center,
              a.justify_between,
              a.gap_sm,
            ]}
          >
            <CardRowTitle>@{peer.handle}</CardRowTitle>
            {lastMessage && (
              <Text style={[a.text_sm, t.atoms.text_contrast_medium]}>
                {formatShortDate(lastMessage.createdAt)}
              </Text>
            )}
          </View>
          <Text
            emoji
            numberOfLines={1}
            style={t.atoms.text_contrast_medium}
          >
            {lastMessage?.text ?? 'No messages yet'}
            {unreadCount > 0 && ` · ${unreadCount} new`}
          </Text>
        </CardRow>
      )}
    </Link>
  )
}

export const ConversationList = ({
  conversations,
  loading,
  emptyMessage = 'No messages yet',
}: {
  conversations: DmConversation[]
  loading?: boolean
  emptyMessage?: string
}) => (
  <List
    items={conversations}
    loading={loading}
    emptyMessage={emptyMessage}
    renderItem={(conversation) => (
      <ConversationRow conversation={conversation} />
    )}
  />
)
