import { Feather } from '@expo/vector-icons'
import { Link, router } from 'expo-router'
import { Dimensions, 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 type { Account, Status } from 'src/lib/api-types'
import { ICON } from 'src/lib/icons'
import { toImageUri } from 'src/lib/media-source'
import {
  getReplyCount,
  preprocessStatusContent,
  prettyCount,
  safeOpenOriginUrl,
  timeAgo,
} from 'src/utils'
import { Separator, Text, useTheme, View, XStack, YStack } from 'tamagui'

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

function hostnameFrom(url: string | null | undefined): string | null {
  if (!url) return null
  try {
    return new URL(url).hostname
  } catch {
    return null
  }
}

type ArticleDetailViewProps = {
  post: Status
  // Phase 4.1a — when embedded inside the merged `/post/[id]` thread view
  // the comments link below the body would route back to the same screen
  // (no-op visual loop), so the screen suppresses it. The standalone
  // `/article/[id]` route still surfaces it as the entry into the thread.
  hideCommentsLink?: boolean
}

function AuthorChip({ account }: { account: Account }) {
  const theme = useTheme()
  return (
    <Link href={`/profile/${account.id}`} asChild>
      <Pressable>
        <XStack alignItems="center" gap="$2">
          <UserAvatar url={account.avatar} size="sm" />
          <YStack flexShrink={1}>
            <EmojiText
              variant="subhead"
              text={account.display_name || account.acct}
              emojis={account.emojis}
              fontWeight="600"
              numberOfLines={1}
            />
            <Text fontSize="$2" color={theme.colorTertiary.val} numberOfLines={1}>
              @{account.acct}
            </Text>
          </YStack>
        </XStack>
      </Pressable>
    </Link>
  )
}

export default function ArticleDetailView({
  post,
  hideCommentsLink,
}: ArticleDetailViewProps) {
  const theme = useTheme()
  const article = post.pf_article
  if (!article) return null

  const authorsFromArticle = article.authors ?? []
  const authors: Account[] =
    authorsFromArticle.length > 0 ? authorsFromArticle : [post.account]
  const primaryAuthor = authors[0]

  const originUrl =
    article.canonical_url ?? post.pf_source?.remote_url ?? post.url ?? null
  const originHost = hostnameFrom(originUrl)
  const isRemote = !!post.pf_source?.platform && post.pf_source.platform !== 'pixelfed'

  const leadImage = post.media_attachments?.[0]
  const hasLeadImage = leadImage?.type === 'image' && leadImage.url

  // Strip Pixelfed's quote-inline / summary-hint cruft the same way posts do
  // elsewhere. Articles occasionally have inline <img>/<figure> tags that
  // we can't render inline yet — StatusContent's html→text conversion drops
  // them along with other markup.
  const bodyHtml = preprocessStatusContent(post.content ?? '')

  const replyCount = getReplyCount(post)
  const readingTime = article.reading_time_minutes
  const wordCount = article.word_count

  const gotoProfileByUsername = (username: string) =>
    router.push(`/profile/0?byUsername=${username.slice(1)}`)
  const gotoHashtag = (tag: string) => router.push(`/hashtag/${tag}`)
  const mentionPress = onMentionPressMethod(
    gotoProfileByUsername,
    post.account?.url ?? `https://${originHost ?? ''}`
  )

  return (
    <YStack backgroundColor={theme.background.val}>
      {hasLeadImage ? (
        <ImageComponent
          source={{
            uri: toImageUri(leadImage!),
            width: SCREEN_WIDTH,
            height: 220,
          }}
          style={{ width: '100%', height: 220 } as any}
          resizeMode={'cover' as any}
        />
      ) : null}

      <YStack padding={16} gap="$3">
        <XStack alignItems="center" gap="$2">
          <Feather name="file-text" size={ICON.xs} color={theme.colorTertiary.val} />
          <Text fontSize="$2" color={theme.colorTertiary.val}>
            Article
          </Text>
          {post.created_at ? (
            <Text fontSize="$2" color={theme.colorTertiary.val}>
              · {timeAgo(post.created_at)}
            </Text>
          ) : null}
        </XStack>

        <Text fontSize="$8" fontWeight="bold" color={theme.color.val}>
          {article.name}
        </Text>

        {readingTime || wordCount ? (
          <XStack gap="$3" alignItems="center">
            {readingTime ? (
              <XStack alignItems="center" gap="$1">
                <Feather name="clock" size={ICON.xs} color={theme.colorTertiary.val} />
                <Text fontSize="$2" color={theme.colorTertiary.val}>
                  {readingTime} min read
                </Text>
              </XStack>
            ) : null}
            {wordCount ? (
              <Text fontSize="$2" color={theme.colorTertiary.val}>
                {prettyCount(wordCount)} words
              </Text>
            ) : null}
          </XStack>
        ) : null}

        {primaryAuthor ? (
          <YStack gap="$2" marginTop="$1">
            <Separator borderColor={theme.borderColor.val} />
            <YStack paddingTop="$2" gap="$2">
              {authors.map((a) => (
                <AuthorChip key={a.id ?? a.acct} account={a} />
              ))}
            </YStack>
          </YStack>
        ) : null}

        {bodyHtml ? (
          <YStack gap="$1" marginTop="$2">
            <Separator borderColor={theme.borderColor.val} />
            <View marginTop="$2">
              <StatusContent
                html={bodyHtml}
                emojis={post.emojis}
                onMentionPress={mentionPress}
                onHashtagPress={gotoHashtag}
              />
            </View>
          </YStack>
        ) : null}

        <YStack gap="$2" marginTop="$2">
          <Separator borderColor={theme.borderColor.val} />
          {hideCommentsLink ? null : (
            <Pressable onPress={() => router.push(`/post/${post.id}`)}>
              <View
                padding={12}
                borderRadius={8}
                backgroundColor={theme.backgroundTertiary.val}
              >
                <XStack alignItems="center" gap="$2">
                  <Feather
                    name="message-circle"
                    size={ICON.sm}
                    color={theme.interactiveActive.val}
                  />
                  <Text fontSize="$3" color={theme.interactiveActive.val}>
                    {replyCount > 0
                      ? `View comments · ${prettyCount(replyCount)}`
                      : 'Be the first to comment'}
                  </Text>
                </XStack>
              </View>
            </Pressable>
          )}

          {originUrl && isRemote ? (
            <Pressable onPress={() => safeOpenOriginUrl(originUrl, post.uri)}>
              <View
                padding={12}
                borderRadius={8}
                backgroundColor={theme.backgroundTertiary.val}
              >
                <XStack alignItems="center" gap="$2">
                  <Feather
                    name="external-link"
                    size={ICON.sm}
                    color={theme.interactiveActive.val}
                  />
                  <Text fontSize="$3" color={theme.interactiveActive.val}>
                    Open on {originHost ?? 'origin'}
                  </Text>
                </XStack>
              </View>
            </Pressable>
          ) : null}
        </YStack>
      </YStack>
    </YStack>
  )
}
