import { useQuery } from '@tanstack/react-query'
import { router } from 'expo-router'
import { Dimensions, 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 type { Quote, ShallowQuote, Status } from 'src/lib/api-types'
import { toImageUri } from 'src/lib/media-source'
import { postQueries } from 'src/lib/queries/posts'
import { htmlToTextWithLineBreaks, preprocessStatusContent, timeAgo } from 'src/utils'
import { Text, useTheme, View, XStack, YStack } from 'tamagui'

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

type QuotedStatusProps = {
  quote: Quote | ShallowQuote
}

function placeholderCopy(state: Quote['state']): string | null {
  switch (state) {
    case 'pending':
      return 'Quote pending approval from the original author.'
    case 'rejected':
      return 'Quote declined by the original author.'
    case 'revoked':
      return 'The original author revoked this quote.'
    case 'deleted':
      return 'The quoted post was deleted.'
    case 'unauthorized':
      return "You don't have permission to view this quote."
    case 'blocked_account':
      return 'Quoted account is blocked.'
    case 'blocked_domain':
      return 'Quoted domain is blocked.'
    case 'muted_account':
      return 'Quoted account is muted.'
    default:
      return null
  }
}

function isDeepQuote(q: Quote | ShallowQuote): q is Quote {
  return 'quoted_status' in q && !!q.quoted_status
}

function isShallowQuote(q: Quote | ShallowQuote): q is ShallowQuote {
  return 'quoted_status_id' in q && !!q.quoted_status_id
}

export default function QuotedStatus({ quote }: QuotedStatusProps) {
  const theme = useTheme()

  const shallowId =
    !isDeepQuote(quote) && isShallowQuote(quote)
      ? (quote as ShallowQuote).quoted_status_id
      : undefined

  const backfill = useQuery({
    ...postQueries.detail(shallowId ?? ''),
    enabled: !!shallowId && quote.state === 'accepted',
  })

  const status: Status | undefined = isDeepQuote(quote)
    ? quote.quoted_status
    : (backfill.data as Status | undefined)

  if (quote.state !== 'accepted') {
    const copy = placeholderCopy(quote.state)
    if (!copy) return null
    return <PlaceholderCard text={copy} theme={theme} />
  }

  if (!status) {
    if (backfill.isError) {
      return <PlaceholderCard text="Quoted post unavailable." theme={theme} />
    }
    return <PlaceholderCard text="Loading quoted post…" theme={theme} muted />
  }

  const captionRaw = preprocessStatusContent(status.content ?? '')
  const caption = htmlToTextWithLineBreaks(captionRaw)
  const firstMedia = status.media_attachments?.[0]
  const isSensitive = status.sensitive === true

  return (
    <Pressable onPress={() => router.push(`/post/${status.id}`)} hitSlop={4}>
      <View
        borderWidth={1}
        borderColor={theme.borderColor.val}
        borderRadius={12}
        overflow="hidden"
        marginHorizontal={10}
        marginVertical={8}
        backgroundColor={theme.background.val}
      >
        <XStack padding={10} gap="$2" alignItems="center">
          <UserAvatar url={status.account.avatar} size="sm" />
          <YStack flexShrink={1} flexGrow={1}>
            <EmojiText
              variant="subhead"
              text={status.account.display_name?.trim() || status.account.acct}
              emojis={status.account.emojis}
              fontWeight="600"
              color={theme.colorSecondary.val}
              numberOfLines={1}
            />
            <Text fontSize="$2" color={theme.colorTertiary.val}>
              {timeAgo(status.created_at)}
            </Text>
          </YStack>
        </XStack>

        {firstMedia?.url && !isSensitive && (
          <ImageComponent
            source={{
              uri: toImageUri(firstMedia),
              width: SCREEN_WIDTH - 20,
              height: 180,
            }}
            style={{ width: '100%', height: 180 } as any}
            resizeMode={'cover' as any}
          />
        )}

        {isSensitive && (
          <View
            paddingVertical={16}
            paddingHorizontal={12}
            backgroundColor={theme.backgroundTertiary.val}
            alignItems="center"
          >
            <EmojiText
              variant="body"
              text={status.spoiler_text?.trim() || 'Sensitive content — tap to view'}
              emojis={status.emojis}
              color={theme.colorSecondary.val}
            />
          </View>
        )}

        {!!caption && (
          <YStack paddingHorizontal={12} paddingVertical={10}>
            <EmojiText
              variant="body"
              text={caption}
              emojis={status.emojis}
              numberOfLines={2}
            />
          </YStack>
        )}
      </View>
    </Pressable>
  )
}

function PlaceholderCard({
  text,
  theme,
  muted = false,
}: {
  text: string
  theme: ReturnType<typeof useTheme>
  muted?: boolean
}) {
  return (
    <View
      borderWidth={1}
      borderColor={theme.borderColor.val}
      borderRadius={12}
      marginHorizontal={10}
      marginVertical={8}
      paddingVertical={14}
      paddingHorizontal={12}
      backgroundColor={theme.backgroundTertiary.val}
      opacity={muted ? 0.7 : 1}
    >
      <Text fontSize="$3" color={theme.colorSecondary.val}>
        {text}
      </Text>
    </View>
  )
}
