import { Link, router } from 'expo-router'
import { useCallback, useMemo } from 'react'
import { Pressable } from 'react-native'
import { onMentionPressMethod } from 'src/components/common/AutolinkText'
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 {
  ModerationWarningPanel,
  SeveredRelationshipsPanel,
} from 'src/components/notifications/NotificationPayloadPanels'
import { toImageUri } from 'src/lib/media-source'
import {
  isUnread,
  markNotificationReadOnTap,
  useActiveLocalMarker,
} from 'src/lib/notifications/marker'
import { enforceLen, timeAgo } from 'src/utils'
import { Text, useTheme, View, XStack, YStack } from 'tamagui'

interface RenderItemProps {
  item: any
}

const eventName = (item: any): string =>
  item?.status?.pf_event?.name || item?.pf_event?.name || 'an event'

const rsvpStatusLabel = (item: any): string => {
  const status: string | undefined = item?.meta?.status || item?.rsvp?.status
  if (status === 'going') return 'going'
  if (status === 'interested') return 'interested'
  if (status === 'declined') return 'no longer going'
  return 'responding'
}

const _msgText = (item: any): string => {
  switch (item?.type) {
    case 'like':
    case 'favourite':
      return 'liked a post'

    case 'follow':
      return 'followed you'

    case 'follow_request':
      return 'requested to follow you'

    case 'mention':
      return 'mentioned you'

    case 'reblog':
      return 'shared your post'

    case 'event:rsvp':
      return `is ${rsvpStatusLabel(item)} to your event`

    case 'event:update':
      return `updated ${eventName(item)}`

    case 'event:cancelled':
      return `cancelled ${eventName(item)}`

    case 'event:comment':
      return `commented on ${eventName(item)}`

    case 'quote':
      return 'quoted your post'

    case 'quoted_update':
      return 'edited a post you quoted'

    case 'severed_relationships':
      return 'Some relationships were severed by moderation action'

    case 'moderation_warning':
      return 'You received a moderation warning'

    case 'poll':
      return 'a poll you voted in has ended'

    case 'status':
      return 'posted a status you subscribed to'

    case 'update':
      return 'edited a post you liked'

    default:
      return ' unknown notification type'
  }
}

const MENTION_EXCERPT_MAX_CHARS = 120

const RenderItem = ({ item }: RenderItemProps) => {
  const theme = useTheme()
  const type = item?.type
  const marker = useActiveLocalMarker()
  const unread = isUnread(String(item.id), marker)

  // Holistic Pass 4 Phase 3.4 — every tap path within the row marks the
  // notification read. The advance is clamp-forward (the helper no-ops when
  // the row id is older than the marker) so older taps after newer ones
  // don't downgrade the marker.
  const onMarkRead = useCallback(() => {
    markNotificationReadOnTap(String(item.id))
  }, [item.id])

  // Holistic Pass 4 Phase 3.5 — for mention rows with a status payload,
  // surface a short excerpt of what was said. Routed through StatusContent
  // so URLs, hashtags, and mentions inside the excerpt are tappable (and
  // custom emojis still render). Press routing inside the excerpt wins the
  // gesture via the inner `Text onPress`; the outer Pressable still
  // navigates to the post when the user taps outside a token.
  const hasMentionExcerpt = type === 'mention' && !!item?.status?.content
  const onHashtagPress = useCallback((tag: string) => {
    router.push(`/hashtag/${tag}`)
  }, [])
  const onMentionPress = useMemo(
    () =>
      onMentionPressMethod(
        (username: string) => router.push(`/profile/0?byUsername=${username}`),
        item?.status?.account?.url ?? '',
        {
          mentions: item?.status?.mentions,
          gotoProfileById: (id: string) => router.push(`/profile/${id}`),
        }
      ),
    [item?.status?.account?.url, item?.status?.mentions]
  )

  return (
    <View
      px="$4"
      py="$2"
      key={item.id}
      borderLeftWidth={unread ? 3 : 0}
      borderLeftColor={unread ? '$interactiveActive' : 'transparent'}
    >
      <XStack justifyContent="space-between" alignItems="center">
        <XStack gap="$3" alignItems="center" flexShrink={1}>
          {item && item.account && item.account?.id && (
            <Link href={`/profile/${item.account.id}`} asChild>
              <Pressable onPress={onMarkRead}>
                <Link.Trigger>
                  <UserAvatar url={item.account.avatar} />
                </Link.Trigger>
                <Link.Preview style={{ width: 320, height: 420 }} />
              </Pressable>
            </Link>
          )}

          <YStack gap={5} flexShrink={1}>
            <XStack gap="$1" alignItems="center">
              <EmojiText
                text={enforceLen(
                  item.account?.display_name || item.account?.acct || '',
                  25,
                  true
                )}
                emojis={item.account?.emojis}
                fontSize="$2"
                fontWeight={'bold'}
                allowFontScaling={false}
                color={theme.color.val}
              />
            </XStack>
            <XStack gap="$1" alignItems="center" flexShrink={1} flexWrap="wrap">
              {item.status ? (
                <Link href={`/post/${item.status.id}`} asChild>
                  <Pressable onPress={onMarkRead}>
                    <Text
                      fontSize="$2"
                      color={theme.interactiveActive.val}
                      fontWeight="bold"
                      allowFontScaling={false}
                    >
                      {_msgText(item)}
                    </Text>
                  </Pressable>
                </Link>
              ) : (
                <Text fontSize="$2" allowFontScaling={false} color={theme.color.val}>
                  {_msgText(item)}
                </Text>
              )}
              <Text
                ml="$2"
                fontSize="$2"
                color={theme.colorTertiary.val}
                fontWeight={'bold'}
                allowFontScaling={false}
              >
                {timeAgo(item.created_at)}
              </Text>
            </XStack>
            {hasMentionExcerpt ? (
              <StatusContent
                html={item.status.content}
                emojis={item.status?.emojis}
                onHashtagPress={onHashtagPress}
                onMentionPress={onMentionPress}
                thresholdChars={MENTION_EXCERPT_MAX_CHARS}
                disableReadMore
              />
            ) : null}
            {type === 'severed_relationships' ? (
              <SeveredRelationshipsPanel
                event={item?.event || item?.relationship_severance_event}
              />
            ) : null}
            {type === 'moderation_warning' ? (
              <ModerationWarningPanel warning={item?.moderation_warning} />
            ) : null}
          </YStack>
        </XStack>

        {item.status &&
        item.status.media_attachments?.length &&
        item.status.media_attachments[0].type === 'image' ? (
          <Link
            href={`/post/${item.status.in_reply_to_id ? item.status.in_reply_to_id : item.status.id}`}
            asChild
          >
            <Pressable onPress={onMarkRead}>
              <Link.Trigger>
                <ImageComponent
                  placeholder={{
                    blurhash: item?.status?.media_attachments[0]?.blurhash || '',
                  }}
                  source={{ uri: toImageUri(item.status.media_attachments[0]) }}
                  recyclingKey={item.status.id}
                  style={{ width: 50, height: 50, borderRadius: 5 }}
                  contentFit={'cover'}
                />
              </Link.Trigger>
              <Link.Preview style={{ width: 350, height: 450 }} />
            </Pressable>
          </Link>
        ) : null}
      </XStack>
    </View>
  )
}

export default RenderItem
