import { Pressable } from 'react-native'
import {
  BASE_LEFT_PADDING,
  resolvedLeftInset,
  STRIPE_WIDTH,
  useThreadRowStyle,
} from 'src/components/comments/threadStyle'
import EmojiText from 'src/components/common/EmojiText'
import StatusContent from 'src/components/common/StatusContent'
import StatusMediaPreview from 'src/components/common/StatusMediaPreview'
import UserAvatar from 'src/components/common/UserAvatar'
import { useWindowWidth } from 'src/hooks/useWindowWidth'
import { getReplyCount, prettyCount, timeAgo } from 'src/utils'
import { Text, useTheme, View, XStack, YStack } from 'tamagui'
import { onMentionPressMethod } from '../common/AutolinkText'
import { CommentItemKebab } from './CommentItemKebab'

// Fixed column widths used to compute available media width. Sourced from
// `UserAvatar` size="md" (40px), the `gap="$3"` between avatar and body
// (~12px), and the kebab's effective hit-target (~36px).
const AVATAR_PX = 40
const AVATAR_GAP = 12
const KEBAB_PX = 36
const RIGHT_PADDING = 15

export default function CommentItem({
  item,
  onReply,
  onLike,
  onReport,
  onDelete,
  onShowLikes,
  onViewReplies,
  viewRepliesLabel,
  gotoProfile,
  gotoUsernameProfile,
  gotoHashtag,
  user,
  depth = 0,
}: {
  item: any
  onReply: any
  onLike: any
  onReport: any
  onDelete: any
  onShowLikes: any
  onViewReplies?: (item: any) => void
  // Explicit label for callers that want "Open this reply →" (ancestors) or
  // any other variant. When omitted, the affordance auto-labels from the
  // reply count: "View N reply/replies →".
  viewRepliesLabel?: string
  gotoProfile: any
  gotoUsernameProfile: any
  gotoHashtag: any
  user: any
  depth?: number
}) {
  const theme = useTheme()
  const windowWidth = useWindowWidth()
  // Per-row stripe + bounded indent — `f(depth, activeAccent)`. Ancestors
  // (depth=0) get no stripe and no extra padding; descendants step in
  // `INDENT_STEP` per level up to `INDENT_CAP`, alpha follows a smoothstep
  // curve so deeper rows recede visually.
  const rowStyle = useThreadRowStyle(depth)
  const leftInset = resolvedLeftInset(depth)
  // Width budget for inline media: window − left inset − right padding
  // − stripe (when present) − avatar column − gap − kebab.
  const stripeWidth = depth > 0 ? STRIPE_WIDTH : 0
  const mediaWidth = Math.max(
    160,
    windowWidth -
      leftInset -
      RIGHT_PADDING -
      stripeWidth -
      AVATAR_PX -
      AVATAR_GAP -
      KEBAB_PX
  )

  const isLiked = !!item.favourited
  const likeCount = item.favourites_count ?? 0
  const replyCount = getReplyCount(item)
  const showRepliesLink =
    !!onViewReplies && (viewRepliesLabel !== undefined || replyCount > 0)
  const repliesLabelResolved =
    viewRepliesLabel ??
    (replyCount > 0
      ? `View ${prettyCount(replyCount)} ${replyCount === 1 ? 'reply' : 'replies'} →`
      : 'View thread →')

  return (
    <View
      flex={1}
      paddingLeft={depth > 0 ? undefined : BASE_LEFT_PADDING}
      paddingRight={RIGHT_PADDING}
      paddingVertical={15}
      marginBottom={0}
      bg="$background"
      {...rowStyle}
    >
      <XStack flexShrink={1}>
        <XStack gap="$3" flexGrow={1} flexShrink={1}>
          <UserAvatar
            url={item.account.avatar}
            onPress={() => gotoProfile(item.account.id)}
            hitSlop={8}
            size="md"
          />

          <YStack flexGrow={1} flexShrink={1} gap={4}>
            <Pressable
              onPress={() => gotoProfile(item?.account.id)}
              hitSlop={7}
              style={{ flexShrink: 1 }}
            >
              <EmojiText
                variant="subhead"
                text={item.account.display_name || item.account.acct}
                emojis={item.account.emojis}
                fontWeight="600"
                numberOfLines={1}
              />
            </Pressable>

            {item.media_attachments?.length > 0 && (
              <StatusMediaPreview status={item} width={mediaWidth} maxHeight={360} />
            )}

            <StatusContent
              html={item.content ?? ''}
              thresholdChars={280}
              onMentionPress={onMentionPressMethod(
                gotoUsernameProfile,
                item.account.url,
                {
                  mentions: item.mentions,
                  gotoProfileById: gotoProfile,
                }
              )}
              onHashtagPress={gotoHashtag}
            />

            <XStack mt="$2" gap="$4" rowGap="$2" flexWrap="wrap" alignItems="center">
              <Pressable onPress={() => onReply(item)} hitSlop={7}>
                <Text fontWeight="bold" fontSize="$3" color={theme.colorSecondary.val}>
                  Reply
                </Text>
              </Pressable>
              <Pressable onPress={() => onLike(item)} hitSlop={7}>
                <Text
                  fontWeight="bold"
                  fontSize="$3"
                  color={isLiked ? theme.accent.val : theme.colorSecondary.val}
                >
                  {isLiked
                    ? likeCount > 0
                      ? `Liked · ${prettyCount(likeCount)}`
                      : 'Liked'
                    : 'Like'}
                </Text>
              </Pressable>
              <Text fontSize="$3" color={theme.colorTertiary.val}>
                {timeAgo(item.created_at)}
              </Text>
              {showRepliesLink && (
                <Pressable onPress={() => onViewReplies?.(item)} hitSlop={7}>
                  <Text
                    fontWeight="600"
                    fontSize="$3"
                    color={theme.interactiveActive.val}
                  >
                    {repliesLabelResolved}
                  </Text>
                </Pressable>
              )}
            </XStack>
          </YStack>
        </XStack>

        <View>
          <CommentItemKebab
            item={item}
            viewerId={user?.id}
            onReport={onReport}
            onDelete={onDelete}
            onShowLikes={onShowLikes}
          />
        </View>
      </XStack>
    </View>
  )
}
