import {
  segmentByFacets,
  type MentionFacet,
} from '@crumbs/core/mentions'
import type {TrailPost} from '@crumbs/core/schemas'
import {useRouter} from 'expo-router'
import {Fragment} from 'react'
import {Pressable, View} from 'react-native'

import {type EmptyStateAction} from '@/components/empty-state'
import {Avatar} from '@/components/ui/avatar'
import {CardRow, CardRowTitle} from '@/components/ui/card'
import {List} from '@/components/ui/list'
import {Text} from '@/components/ui/typography'
import {formatShortDate} from '@/lib/dates'
import {atoms as a, useTheme} from '@/sprinkles'

// post body with tappable @mentions, resolved from stored facets
export const RichPostText = ({
  text,
  facets,
  numberOfLines,
}: {
  text: string
  facets: MentionFacet[]
  numberOfLines?: number
}) => {
  const t = useTheme()
  const router = useRouter()
  return (
    <Text
      numberOfLines={numberOfLines}
      style={[a.text_md, a.leading_normal]}
    >
      {segmentByFacets(text, facets).map((segment, i) =>
        segment.facet ? (
          <Text
            key={i}
            accessibilityRole="link"
            style={[a.text_md, {color: t.palette.primary_500}]}
            onPress={() =>
              router.push(`/profile/${segment.facet!.userId}`)
            }
          >
            {segment.text}
          </Text>
        ) : (
          <Fragment key={i}>{segment.text}</Fragment>
        ),
      )}
    </Text>
  )
}

// one post row, reusable by any list container (List, VirtualList)
export const TrailPostRow = ({
  post,
  onLongPress,
  numberOfLines,
}: {
  post: TrailPost
  onLongPress?: (post: TrailPost) => void
  numberOfLines?: number
}) => {
  const t = useTheme()
  return (
    <Pressable
      accessibilityLabel={`Post by @${post.author.handle}`}
      accessibilityHint={
        onLongPress ? 'Long press for options' : undefined
      }
      onLongPress={onLongPress && (() => onLongPress(post))}
    >
      <CardRow
        leading={
          <View style={a.align_self_start}>
            <Avatar
              handle={post.author.handle}
              uri={post.author.avatarUrl}
              size={36}
            />
          </View>
        }
        trailing={null}
      >
        <View style={[a.flex_row, a.align_center, a.gap_sm]}>
          <CardRowTitle>@{post.author.handle}</CardRowTitle>
          <Text style={[a.text_sm, t.atoms.text_contrast_medium]}>
            {formatShortDate(post.createdAt)}
          </Text>
        </View>
        <RichPostText
          text={post.text}
          facets={post.facets}
          numberOfLines={numberOfLines}
        />
      </CardRow>
    </Pressable>
  )
}

export const TrailPostList = ({
  posts,
  loading,
  loadingMore,
  emptyMessage = 'No posts yet',
  emptyAction,
  onPostLongPress,
}: {
  posts: TrailPost[]
  loading?: boolean
  loadingMore?: boolean
  emptyMessage?: string
  emptyAction?: EmptyStateAction
  onPostLongPress?: (post: TrailPost) => void
}) => (
  <List
    items={posts}
    loading={loading}
    loadingMore={loadingMore}
    emptyMessage={emptyMessage}
    emptyAction={emptyAction}
    renderItem={(post) => (
      <TrailPostRow post={post} onLongPress={onPostLongPress} />
    )}
  />
)
