import { Feather } from '@expo/vector-icons'
import { Link, useRouter } from 'expo-router'
import { useCallback, useMemo } from 'react'
import { Platform, Pressable } from 'react-native'
import { onMentionPressMethod } from 'src/components/common/AutolinkText'
import EmojiText from 'src/components/common/EmojiText'
import { Favicon } from 'src/components/common/Favicon'
import { PressableOpacity } from 'src/components/common/PressableOpacity'
import StatusContent from 'src/components/common/StatusContent'
import UserAvatar from 'src/components/common/UserAvatar'
import ProfileFields from 'src/components/profile/ProfileFields'
import { useImageViewer } from 'src/hooks/useImageViewer'
import type { Relationship } from 'src/lib/api-types'
import { ICON } from 'src/lib/icons'
import { normalizeAccountFields } from 'src/lib/profile/accountFields'
import { formatLink } from 'src/lib/url-format'
import { enforceLen, openBrowserAsync, prettyCount } from 'src/utils'
import { Text, useTheme, View, XStack, YStack } from 'tamagui'

type todo = any

// Mastodon verifies profile links per-field (rel="me"), not per-account, so the
// per-field check next to each verified field is the canonical surface. This
// flag additionally shows a small check beside the display name when ANY field
// is verified — a Halflight enhancement, off by default to match upstream.
const SHOW_ACCOUNT_VERIFIED_BADGE = false

interface ProfileHeaderProps {
  profile: todo
  relationship?: Relationship
  mutuals: todo[]
}

// TODO split self profile and other user profile
// Why? because they have different required properties
export default function ProfileHeader({
  profile,
  relationship,
  mutuals,
}: ProfileHeaderProps) {
  const router = useRouter()
  const { open: openImageViewer } = useImageViewer()

  const theme = useTheme()

  // Stable callbacks: passed through to <StatusContent> via `RenderBio`'s
  // useCallback. Recreating these on every render busted RenderBio's memo
  // and contributed to the bio "View More" state evaporating during
  // FlashList header churn (Phase 2.4 — Thread F).
  const onHashtagPress = useCallback(
    (tag: string) => {
      router.push(`/hashtag/${tag}`)
    },
    [router]
  )

  const onMentionPress = useCallback(
    (tag: string) => {
      router.push(`/profile/0?byUsername=${tag.slice(1)}`)
    },
    [router]
  )

  const profileUrl: string = profile?.url ?? ''
  const memoMentionPress = useMemo(
    () => onMentionPressMethod(onMentionPress, profileUrl),
    [onMentionPress, profileUrl]
  )

  const _openWebsite = async () => {
    await openBrowserAsync(profile?.website)
  }

  const renderMutualSeparator = (index: number) => {
    const top3 = mutuals.slice(0, 3)
    const totalLen = mutuals.length

    if (totalLen === 1) {
      return
    }

    if (totalLen === 3) {
      if (index != top3.length - 1) {
        return index === top3.length - 2 ? ' and ' : ', '
      }
      return ' '
    }

    if (totalLen < 4) {
      return index != top3.length - 1 ? ' and ' : ' '
    }
    return index != top3.length - 1 ? ', ' : ' '
  }

  const RenderMutuals = useCallback(() => {
    const top3 = mutuals.slice(0, 3)
    return (
      <XStack alignItems="center" gap="$2" mt="$3" mb="$1">
        <XStack gap={-10}>
          {top3.map((m) => (
            <UserAvatar key={m.id} url={m.avatar} size="xs" />
          ))}
        </XStack>
        <XStack maxWidth="80%" flexWrap="wrap">
          <Text fontSize="$2" allowFontScaling={false} color={theme.colorSecondary.val}>
            Followed by{' '}
          </Text>
          {top3.map((t, index) => (
            <Link key={index} href={`/profile/${t.id}`} asChild>
              <Pressable>
                <XStack>
                  <Text
                    fontWeight="bold"
                    fontSize="$3"
                    allowFontScaling={false}
                    color={theme.color.val}
                  >
                    {t.username}
                  </Text>
                  <Text
                    fontSize="$3"
                    allowFontScaling={false}
                    color={theme.colorSecondary.val}
                  >
                    {renderMutualSeparator(index)}
                  </Text>
                </XStack>
              </Pressable>
            </Link>
          ))}
          {top3.length === 3 && mutuals.length > 3 ? (
            <Link href={`/profile/followers/${profile?.id}`} asChild>
              <Pressable>
                <Text fontSize="$3" allowFontScaling={false} color={theme.color.val}>
                  and{' '}
                  <Text fontWeight="bold" color={theme.color.val}>
                    {mutuals.length - top3.length} others
                  </Text>
                </Text>
              </Pressable>
            </Link>
          ) : null}
        </XStack>
      </XStack>
    )
  }, [mutuals])

  const RenderBio = useCallback(() => {
    return (
      <StatusContent
        html={profile?.note ?? ''}
        emojis={profile?.emojis}
        thresholdChars={160}
        // Persist View More state across FlashList recycler unmounts and
        // the `key={activeTab}` remount on profile-tab switches. Keyed by
        // profile.id so two profiles' bios don't share state.
        expansionKey={profile?.id ? `bio:${profile.id}` : undefined}
        onHashtagPress={onHashtagPress}
        onMentionPress={memoMentionPress}
      />
    )
  }, [profile, onHashtagPress, memoMentionPress])

  const actorType: string | undefined = profile?.pf_source?.actor_type
  const isCommunityActor = actorType === 'Group' || actorType === 'Organization'
  const communityLabel = actorType === 'Organization' ? 'Organization' : 'Community'
  const upcomingEventsCount: number | null =
    typeof profile?.upcoming_events_count === 'number'
      ? profile.upcoming_events_count
      : null

  // Mastodon structured profile metadata. Empty on Pixelfed (fields: []), so
  // ProfileFields renders nothing there — data-driven, no protocol gate.
  const accountFields = useMemo(() => normalizeAccountFields(profile), [profile])

  return (
    <View flex={1} bg={theme.background.val} pb="$4">
      <View mx="$4" mt={Platform.OS === 'ios' ? '$3' : 0}>
        <XStack w="100%" justifyContent="space-between" alignItems="center" mt="$3">
          <UserAvatar
            url={profile?.avatar}
            size="lg"
            onPress={() =>
              profile?.avatar ? openImageViewer({ uri: profile.avatar }) : undefined
            }
            hitSlop={4}
          />

          <XStack gap="$5" $gtSm={{ gap: '$7' }} mx="$5" alignItems="flex-start">
            <YStack alignItems="center" gap="$1">
              <Text
                fontWeight="bold"
                fontSize="$5"
                allowFontScaling={false}
                color={theme.color.val}
              >
                {prettyCount(profile?.statuses_count ? profile.statuses_count : 0)}
              </Text>
              <Text
                fontSize="$2"
                allowFontScaling={false}
                color={theme.colorSecondary.val}
              >
                Posts
              </Text>
            </YStack>

            {profile && profile.id ? (
              <PressableOpacity
                hitSlop={9}
                onPress={() => router.push(`/profile/following/${profile?.id}`)}
              >
                <YStack alignItems="center" gap="$1">
                  <Text
                    fontWeight="bold"
                    fontSize="$5"
                    allowFontScaling={false}
                    color={theme.color.val}
                  >
                    {prettyCount(profile?.following_count ? profile.following_count : 0)}
                  </Text>
                  <Text
                    fontSize="$2"
                    allowFontScaling={false}
                    color={theme.colorSecondary.val}
                  >
                    Following
                  </Text>
                </YStack>
              </PressableOpacity>
            ) : (
              <YStack alignItems="center" gap="$1">
                <Text
                  fontWeight="bold"
                  fontSize="$5"
                  allowFontScaling={false}
                  color={theme.color.val}
                >
                  0
                </Text>
                <Text
                  fontSize="$2"
                  allowFontScaling={false}
                  color={theme.colorSecondary.val}
                >
                  Following
                </Text>
              </YStack>
            )}

            {profile && profile.id ? (
              <PressableOpacity
                hitSlop={9}
                onPress={() => router.push(`/profile/followers/${profile?.id}`)}
              >
                <YStack alignItems="center" gap="$1">
                  <Text
                    fontWeight="bold"
                    fontSize="$5"
                    allowFontScaling={false}
                    color={theme.color.val}
                  >
                    {prettyCount(profile?.followers_count ? profile.followers_count : 0)}
                  </Text>
                  <Text
                    fontSize="$2"
                    allowFontScaling={false}
                    color={theme.colorSecondary.val}
                  >
                    Followers
                  </Text>
                </YStack>
              </PressableOpacity>
            ) : (
              <YStack alignItems="center" gap="$1">
                <Text
                  fontWeight="bold"
                  fontSize="$6"
                  allowFontScaling={false}
                  color={theme.color.val}
                >
                  0
                </Text>
                <Text
                  fontSize="$3"
                  allowFontScaling={false}
                  color={theme.colorSecondary.val}
                >
                  Followers
                </Text>
              </YStack>
            )}
          </XStack>
        </XStack>

        <YStack w="100%" mt="$3" gap={5}>
          <XStack gap="$2" alignItems="center">
            <EmojiText
              variant="display"
              text={profile?.display_name}
              emojis={profile?.emojis}
              flexWrap="wrap"
            />
            {SHOW_ACCOUNT_VERIFIED_BADGE && accountFields.hasVerifiedField ? (
              <Feather
                name="check-circle"
                size={ICON.xs}
                color={theme.green9?.val ?? '#2E7D32'}
                accessibilityLabel="Has verified links"
              />
            ) : null}
            {profile?.locked && (
              <Feather
                name="lock"
                size={ICON.xs}
                color={theme.colorSecondary.val}
                style={{ marginLeft: -5 }}
              />
            )}
            {isCommunityActor ? (
              <View
                borderWidth={1}
                borderColor={theme.borderColor.val}
                borderRadius={5}
                px={10}
                py={3}
              >
                <Text color={theme.colorSecondary.val} fontWeight="bold" fontSize="$2">
                  {communityLabel}
                </Text>
              </View>
            ) : null}
            {relationship && relationship?.muting ? (
              <View
                borderWidth={1}
                borderColor={theme.borderColor.val}
                borderRadius={5}
                px={10}
                py={3}
              >
                <Text color={theme.colorSecondary.val} fontWeight="bold" fontSize="$2">
                  Muted
                </Text>
              </View>
            ) : null}
            {profile && profile?.is_admin ? (
              <View bg="$red9" borderRadius={5} px={10} py={3}>
                <Text color={theme.color.val} fontWeight="bold" fontSize="$2">
                  Admin
                </Text>
              </View>
            ) : null}
          </XStack>
          {isCommunityActor && upcomingEventsCount != null ? (
            <XStack alignItems="center" gap="$1" mt={-2}>
              <Feather name="calendar" size={ICON.xs} color={theme.colorSecondary.val} />
              <Text
                fontSize="$3"
                color={theme.colorSecondary.val}
                allowFontScaling={false}
              >
                {upcomingEventsCount === 0
                  ? 'No upcoming events'
                  : upcomingEventsCount === 1
                    ? '1 upcoming event'
                    : `${prettyCount(upcomingEventsCount)} upcoming events`}
              </Text>
            </XStack>
          ) : null}
          {profile && !profile?.local ? (
            <XStack mt={-5} alignItems="center" gap={1}>
              <Feather name="at-sign" color={theme.colorTertiary.val} />
              <Text
                color={theme.color.val}
                fontWeight={300}
                fontSize="$3"
                lineHeight={16}
                mb={1}
                allowFontScaling={false}
                flexWrap="wrap"
              >
                {enforceLen(profile?.acct, 50, true)}
              </Text>
            </XStack>
          ) : null}

          {profile?.note && profile?.note.length && <RenderBio />}

          {profile?.website && profile?.website.trim().length
            ? (() => {
                const formatted = formatLink(profile.website)
                const displayText =
                  formatted?.display ?? profile.website.replace(/^https?:\/\//, '')
                return (
                  <PressableOpacity onPress={() => _openWebsite()}>
                    <XStack alignItems="center" gap="$2">
                      {formatted?.host ? (
                        <Favicon variant="chip" host={formatted.host} size="xs" />
                      ) : null}
                      <Text
                        fontSize="$5"
                        fontWeight={'bold'}
                        color={theme.interactiveActive.val}
                        letterSpacing={-0.34}
                        flexShrink={1}
                      >
                        {displayText}
                      </Text>
                    </XStack>
                  </PressableOpacity>
                )
              })()
            : null}

          {accountFields.fields.length ? (
            <ProfileFields
              fields={accountFields.fields}
              emojis={profile?.emojis}
              onHashtagPress={onHashtagPress}
              onMentionPress={memoMentionPress}
            />
          ) : null}
        </YStack>

        {mutuals && mutuals.length ? (
          <View w="100%" flexGrow={1}>
            <RenderMutuals />
          </View>
        ) : null}
      </View>
    </View>
  )
}
