import { Feather } from '@expo/vector-icons'
import { Pressable } from 'react-native'
import EmojiText from 'src/components/common/EmojiText'
import UserAvatar from 'src/components/common/UserAvatar'
import type { Status } from 'src/lib/api-types'
import { ICON } from 'src/lib/icons'
import { htmlToTextWithLineBreaks, truncateKeepingShortcodes } from 'src/utils'
import { Text, useTheme, View, XStack, YStack } from 'tamagui'

type Props = {
  target: Status | null | undefined
  // Optional clear handler. The route-driven default case has no clear path
  // (the URL param is the source of truth), so the [×] button only renders
  // when the caller provides a handler.
  onClear?: () => void
}

export function ReplyIndicator({ target, onClear }: Props) {
  const theme = useTheme()
  if (!target) return null
  const acct = target.account?.acct ?? ''
  const raw = htmlToTextWithLineBreaks(target.content ?? '').trim()
  // Backs off a `:shortcode:` straddling the cut instead of leaking a
  // bare `:`.
  const snippet = raw ? truncateKeepingShortcodes(raw, 100) : ''
  return (
    <View
      mt="$3"
      borderWidth={1}
      borderColor={theme.borderColor.val}
      borderRadius={10}
      backgroundColor={theme.backgroundTertiary.val}
      p="$3"
    >
      <XStack gap="$3">
        <UserAvatar url={target.account?.avatar} size="sm" />
        <YStack flex={1}>
          <XStack alignItems="center" gap="$2" justifyContent="space-between">
            <Text fontSize="$2" color={theme.colorTertiary.val} numberOfLines={1}>
              Replying to @{acct}
            </Text>
            {onClear ? (
              <Pressable onPress={onClear} hitSlop={10}>
                <Feather name="x" size={ICON.sm} color={theme.colorSecondary.val} />
              </Pressable>
            ) : null}
          </XStack>
          {snippet ? (
            <EmojiText
              variant="caption"
              text={snippet}
              emojis={target.account?.emojis}
              color={theme.colorTertiary.val}
              numberOfLines={2}
            />
          ) : null}
        </YStack>
      </XStack>
    </View>
  )
}
