import { Dimensions, Pressable } from 'react-native'
import {
  INDENT_CAP,
  INDENT_STEP,
  threadRowStyle,
} from 'src/components/comments/threadStyle'
import EmojiText from 'src/components/common/EmojiText'
import StatusContent from 'src/components/common/StatusContent'
import UserAvatar from 'src/components/common/UserAvatar'
import ImageComponent from 'src/components/ImageComponent'
import { toImageUri } from 'src/lib/media-source'
import { prettyCount, timeAgo } from 'src/utils'
import { Text, useTheme, View, XStack, YStack } from 'tamagui'
import { onMentionPressMethod } from '../common/AutolinkText'
import { CommentItemKebab } from './CommentItemKebab'

const SCREEN_WIDTH = Dimensions.get('screen').width

export default function CommentItem({
  item,
  onReply,
  onLike,
  onReport,
  onDelete,
  onShowLikes,
  onTapRow,
  gotoProfile,
  gotoUsernameProfile,
  gotoHashtag,
  user,
  depth = 0,
}: {
  item: any
  onReply: any
  onLike: any
  onReport: any
  onDelete: any
  onShowLikes: any
  onTapRow?: (item: any) => void
  gotoProfile: any
  gotoUsernameProfile: any
  gotoHashtag: any
  user: any
  depth?: number
}) {
  const theme = useTheme()
  // Per-row stripe + bounded indent — pure function of `depth`.
  // Ancestors / direct-replies (`depth=0`) get no stripe and no extra
  // padding; descendants step in `INDENT_STEP` per level up to the cap.
  // Stripe colour cycles modulo `THREAD_PALETTE.length` past the cap so
  // depth is still legible without burning more horizontal space.
  const rowStyle = threadRowStyle(depth)
  // Mastodon-served comment rows with a single image attachment render
  // the inline thumbnail too; multi-image / video stay text-only.
  const firstAttachment = item.media_attachments?.[0]
  const hasInlineThumbnail = item.pf_type === 'photo' || firstAttachment?.type === 'image'
  const isLiked = !!item.favourited
  const likeCount = item.favourites_count ?? 0

  // Phase 4.1a — tapping a non-anchor row pushes a fresh thread anchored
  // on it, matching mastodon-ios's `openThreadView` shape. The row body
  // is a Pressable for that affordance; the per-row icon buttons stop
  // propagation so they don't double-fire.
  const RowWrap = onTapRow
    ? ({ children }: { children: React.ReactNode }) => (
        <Pressable onPress={() => onTapRow(item)}>{children}</Pressable>
      )
    : ({ children }: { children: React.ReactNode }) => <>{children}</>

  // Reserve enough horizontal room for the indent cap so the body column
  // doesn't bleed under the kebab even at maximum depth.
  const reservedIndent = Math.min(depth, INDENT_CAP) * INDENT_STEP

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

            <YStack flexGrow={1} maxWidth={SCREEN_WIDTH - 150 - reservedIndent} 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>

              {hasInlineThumbnail && firstAttachment?.url && (
                <ImageComponent
                  source={{
                    uri: toImageUri(firstAttachment),
                    width: 200,
                    height: 200,
                  }}
                  style={
                    {
                      width: 200,
                      height: 200,
                      borderRadius: 10,
                    } as any
                  }
                  resizeMode={'cover' as any}
                />
              )}

              <StatusContent
                html={item.content ?? ''}
                thresholdChars={280}
                onMentionPress={onMentionPressMethod(
                  gotoUsernameProfile,
                  item.account.url
                )}
                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>
              </XStack>
            </YStack>
          </XStack>

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