import { Feather } from '@expo/vector-icons'
import {
  BottomSheetBackdrop,
  type BottomSheetModal,
  BottomSheetScrollView,
} from '@gorhom/bottom-sheet'
import { useQuery } from '@tanstack/react-query'
import { Image } from 'expo-image'
import { LinearGradient } from 'expo-linear-gradient'
import { router } from 'expo-router'
import { type Ref, useCallback, useMemo } from 'react'
import { onMentionPressMethod } from 'src/components/common/AutolinkText'
import { PixelfedBottomSheetModal } from 'src/components/common/BottomSheets'
import EmojiText from 'src/components/common/EmojiText'
import StatusContent from 'src/components/common/StatusContent'
import UserAvatar from 'src/components/common/UserAvatar'
import { Card } from 'src/components/ui'
import { getAccountStatusesById } from 'src/lib/api'
import type { Account, Status } from 'src/lib/api-types'
import { queryKeys } from 'src/lib/queries/keys'
import { prettyCount } from 'src/utils'
import { Button, Text, useTheme, View, XStack, YStack } from 'tamagui'

// Inline "peek" for a follow inside the organizer — long-press or tap a row to
// preview the person before deciding which list they belong in, then dismiss
// back to the same scroll position. Deliberately NOT a fork of ProfileHeader
// (which is bound to nav pushes, the image viewer, mutuals, and stat-grid
// routing); it re-expresses the same layout shape from the same primitives at
// a much smaller surface. Network-light: one cached 1-status fetch on open.

const BANNER_HEIGHT = 156

function bannerUrl(account: Account): string | undefined {
  // Mastodon serves `header` / `header_static`; the shared Account type only
  // declares Pixelfed's `header_bg`. Read whichever the server actually sent.
  const a = account as Account & { header_static?: string; header?: string }
  return a.header_static || a.header || a.header_bg || undefined
}

type Props = {
  ref?: Ref<BottomSheetModal | null>
  account: Account | null
  onDismiss: () => void
}

export function OrganizerQuickLookSheet({ ref, account, onDismiss }: Props) {
  const theme = useTheme()
  const snapPoints = useMemo(() => ['65%', '92%'], [])

  const { data: latestStatus } = useQuery({
    queryKey: account
      ? queryKeys.posts.latestByUser(account.id)
      : ['organizer-latest', 'none'],
    queryFn: () =>
      getAccountStatusesById(account!.id, { limit: 1, exclude_replies: true }),
    enabled: !!account,
    staleTime: 5 * 60 * 1000,
    select: (rows: Status[]) => rows[0] ?? null,
  })

  const renderBackdrop = useCallback(
    (props: any) => (
      <BottomSheetBackdrop {...props} disappearsOnIndex={-1} appearsOnIndex={0} />
    ),
    []
  )

  const onHashtagPress = useCallback((tag: string) => {
    router.push(`/hashtag/${tag}` as any)
  }, [])

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

  const memoMentionPress = useMemo(
    () => onMentionPressMethod(onMentionPress, account?.url ?? ''),
    [onMentionPress, account?.url]
  )

  const banner = account ? bannerUrl(account) : undefined

  return (
    <PixelfedBottomSheetModal
      ref={ref}
      index={0}
      snapPoints={snapPoints}
      onDismiss={onDismiss}
      backdropComponent={renderBackdrop}
      backgroundStyle={{ backgroundColor: theme.background.val }}
      handleIndicatorStyle={{ backgroundColor: theme.backgroundTertiary.val }}
    >
      <BottomSheetScrollView style={{ backgroundColor: theme.background.val }}>
        {account ? (
          <YStack pb="$2">
            {/* 1. Header banner */}
            <View height={BANNER_HEIGHT} backgroundColor="$backgroundTertiary">
              {banner ? (
                <Image
                  source={{ uri: banner }}
                  style={{ width: '100%', height: BANNER_HEIGHT }}
                  contentFit="cover"
                  cachePolicy="memory-disk"
                />
              ) : null}
              <LinearGradient
                colors={['transparent', 'rgba(0,0,0,0.42)']}
                style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: 80 }}
              />
            </View>

            {/* 2. Identity strip — overlaps the banner */}
            <XStack px="$4" mt={-40} gap="$3" alignItems="flex-end">
              <UserAvatar url={account.avatar} size="lg" borderStyle="contrast" />
              <YStack flex={1} gap="$1" pb="$2">
                <EmojiText
                  variant="display"
                  text={account.display_name || account.acct}
                  emojis={account.emojis}
                  numberOfLines={1}
                />
                <Text fontSize="$caption" color="$colorSecondary" numberOfLines={1}>
                  @{account.acct}
                </Text>
              </YStack>
            </XStack>

            {/* 3. Stat chips */}
            <XStack px="$4" pt="$3" gap="$2">
              <Card tone="bordered" compact>
                <XStack gap="$2" alignItems="center">
                  <Feather name="users" size={13} color={theme.colorSecondary.val} />
                  <Text fontSize="$caption" color="$color">
                    {prettyCount(account.followers_count ?? 0)} followers
                  </Text>
                </XStack>
              </Card>
              <Card tone="bordered" compact>
                <XStack gap="$2" alignItems="center">
                  <Feather name="user-plus" size={13} color={theme.colorSecondary.val} />
                  <Text fontSize="$caption" color="$color">
                    {prettyCount(account.following_count ?? 0)} following
                  </Text>
                </XStack>
              </Card>
            </XStack>

            {/* 4. Bio */}
            {account.note ? (
              <Card tone="secondary" mx="$4" mt="$3">
                <StatusContent
                  html={account.note}
                  emojis={account.emojis}
                  thresholdChars={160}
                  expansionKey={`organizer-bio:${account.id}`}
                  onHashtagPress={onHashtagPress}
                  onMentionPress={memoMentionPress}
                />
              </Card>
            ) : null}

            {/* 5. Latest post */}
            <Card tone="secondary" mx="$4" mt="$3">
              <Text fontSize="$caption" color="$colorTertiary" pb="$1">
                Latest post
              </Text>
              {latestStatus ? (
                <StatusContent
                  html={latestStatus.content ?? ''}
                  emojis={latestStatus.emojis}
                  thresholdChars={240}
                  expansionKey={`organizer-status:${latestStatus.id}`}
                  onHashtagPress={onHashtagPress}
                  onMentionPress={memoMentionPress}
                />
              ) : (
                <Text fontSize="$body" color="$colorSecondary">
                  No recent post.
                </Text>
              )}
            </Card>

            {/* 6. Footer actions */}
            <XStack mx="$4" mt="$4" mb="$4" gap="$3">
              <Button
                flex={1}
                size="$4"
                chromeless
                onPress={() => router.push(`/profile/${account.id}` as any)}
              >
                <Button.Text color={theme.color.val}>Open profile</Button.Text>
              </Button>
              <Button
                flex={1}
                size="$4"
                backgroundColor="$accent"
                onPress={() => router.push(`/settings/lists/for/${account.id}` as any)}
              >
                <Button.Text color={theme.onAccent.val}>Manage lists</Button.Text>
              </Button>
            </XStack>
          </YStack>
        ) : null}
      </BottomSheetScrollView>
    </PixelfedBottomSheetModal>
  )
}
