import { Link } from 'expo-router'
import { useCallback } from 'react'
import { Pressable } from 'react-native'
import EmojiText from 'src/components/common/EmojiText'
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, htmlToTextWithLineBreaks, 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 2-line excerpt of what was said. Both Pixelfed (with `_pe=1`)
  // and Mastodon populate `notification.status.content` as HTML; the
  // shared `htmlToTextWithLineBreaks` + `<EmojiText>` rendering pair handles
  // custom emojis on both servers.
  const mentionExcerpt =
    type === 'mention' && item?.status?.content
      ? enforceLen(
          htmlToTextWithLineBreaks(item.status.content),
          MENTION_EXCERPT_MAX_CHARS,
          true
        )
      : null

  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>
            {mentionExcerpt ? (
              <EmojiText
                text={mentionExcerpt}
                emojis={item.status?.emojis}
                fontSize="$2"
                color={theme.colorSecondary.val}
                allowFontScaling={false}
                numberOfLines={2}
              />
            ) : 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
