import { Feather } from '@expo/vector-icons'
import { FlashList } from '@shopify/flash-list'
import { useInfiniteQuery } from '@tanstack/react-query'
import { type ErrorBoundaryProps, Link } from 'expo-router'
import { useMemo } from 'react'
import { ActivityIndicator } from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { ErrorState } from 'src/components/common/ErrorState'
import UserAvatar from 'src/components/common/UserAvatar'
import { useScreenMenu, useSearchQuery } from 'src/components/menu'
import { adminQueries } from 'src/lib/queries/admin'
import { enforceLen, prettyCount, timeAgo } from 'src/utils'
import { Separator, Text, useTheme, View, XStack, YStack } from 'tamagui'

export function ErrorBoundary({ error, retry }: ErrorBoundaryProps) {
  return <ErrorState message={error.message} onRetry={retry} />
}

const keyExtractor = (_: any, _index: any) => `user-${_.id}`

export default function Screen() {
  const [query, setQuery] = useSearchQuery()
  const theme = useTheme()
  const muted = theme.colorTertiary.val
  useScreenMenu({
    title: 'Admin · Users',
    intents: [
      {
        kind: 'search',
        placeholder: 'Filter users',
        value: query,
        onChangeText: setQuery,
      },
    ],
  })
  const RenderItem = ({ item }: { item: any }) => (
    <Link href={`/admin/users/show/${item.id}`} asChild>
      <View px="$5" py="$3" bg="$background">
        <XStack alignItems="center" gap="$3">
          <UserAvatar url={item.avatar} size="sm" />
          <YStack gap={3}>
            <Text fontSize="$6">{item.username}</Text>
            <XStack gap="$3">
              <Text color="$gray9">{enforceLen(item.name, 10, true)}</Text>
              <Separator vertical />
              <XStack alignItems="center" gap={4}>
                <Feather name="users" color={muted} />
                <Text color="$gray9" fontSize={10} allowFontScaling={false}>
                  {prettyCount(item.followers_count)}
                </Text>
              </XStack>
              <Separator vertical />
              <XStack alignItems="center" gap={4}>
                <Feather name="user-plus" color={muted} />
                <Text color="$gray9" fontSize={10} allowFontScaling={false}>
                  {prettyCount(item.following_count)}
                </Text>
              </XStack>
              <Separator vertical />
              <XStack alignItems="center" gap={4}>
                <Feather name="clock" color={muted} />
                <Text color="$gray9" fontSize={10} allowFontScaling={false}>
                  {timeAgo(item.created_at)}
                </Text>
              </XStack>
            </XStack>
          </YStack>
        </XStack>
      </View>
    </Link>
  )

  const {
    data,
    error,
    fetchNextPage,
    hasNextPage,
    isFetching,
    isFetchingNextPage,
    status,
  } = useInfiniteQuery(adminQueries.users())

  const flattenedData = useMemo(() => {
    const flat = data?.pages.flatMap((page) => page.data) ?? []
    const q = query.trim().toLowerCase()
    if (!q) return flat
    return flat.filter((item: any) => {
      const username = item?.username?.toLowerCase() ?? ''
      const name = item?.name?.toLowerCase() ?? ''
      return username.includes(q) || name.includes(q)
    })
  }, [data?.pages, query])

  if (status === 'pending' && !isFetchingNextPage) {
    return <ActivityIndicator />
  }

  if (status === 'error') {
    return <Text>{error?.message}</Text>
  }

  return (
    <SafeAreaView edges={['top', 'bottom']}>
      <FlashList
        keyExtractor={keyExtractor}
        data={flattenedData}
        renderItem={RenderItem}
        contentContainerStyle={{ flexGrow: 1 }}
        ItemSeparatorComponent={Separator}
        onEndReached={() => {
          if (!isFetching && hasNextPage && !isFetchingNextPage) fetchNextPage()
        }}
        ListFooterComponent={() =>
          isFetchingNextPage ? (
            <View p="$3">
              <ActivityIndicator />
            </View>
          ) : null
        }
        onEndReachedThreshold={0.5}
      />
    </SafeAreaView>
  )
}
