import { FlashList } from '@shopify/flash-list'
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
import { Link, Stack, useLocalSearchParams } from 'expo-router'
import { useMemo } from 'react'
import { Pressable } from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { ErrorState } from 'src/components/common/ErrorState'
import { ListFooter } from 'src/components/common/ListFooter'
import { LoadingView } from 'src/components/common/LoadingView'
import { UserRow } from 'src/components/common/UserRow'
import { useScreenMenu, useSearchQuery } from 'src/components/menu'
import { postQueries } from 'src/lib/queries/posts'
import { Separator } from 'tamagui'

type Props = {
  type: 'likes' | 'shares'
}

export function PostInteractionList({ type }: Props) {
  const { id } = useLocalSearchParams<{ id: string }>()
  const [query, setQuery] = useSearchQuery()

  const { data: status } = useQuery(postQueries.detail(id))
  const statusId = status?.id

  const {
    data: feed,
    fetchPreviousPage,
    hasPreviousPage,
    isFetchingPreviousPage,
    isFetching,
    error,
    refetch,
  } = useInfiniteQuery({
    ...(postQueries[type](statusId as string) as ReturnType<typeof postQueries.likes>),
    select: (data) => ({
      pages: [...data.pages].reverse(),
      pageParams: [...data.pageParams].reverse(),
    }),
    enabled: !!status,
  })

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

  const count = type === 'likes' ? status?.favourites_count : status?.reblogs_count
  const label = type === 'likes' ? 'Likes' : 'Shares'
  const title = status ? `${label} (${count})` : label

  useScreenMenu({
    title,
    intents: [
      { kind: 'back' },
      {
        kind: 'search',
        placeholder: `Filter ${label.toLowerCase()}`,
        value: query,
        onChangeText: setQuery,
      },
    ],
  })

  if (isFetching && !isFetchingPreviousPage) return <LoadingView />
  if (error) return <ErrorState onRetry={refetch} />

  return (
    <SafeAreaView style={{ flex: 1 }} edges={['bottom']}>
      <Stack.Screen options={{ title, headerBackTitle: 'Back' }} />
      <FlashList
        data={flattenedData}
        renderItem={({ item }) => (
          <Link href={`/profile/${item.id}`} asChild>
            <Pressable>
              <UserRow account={item} />
            </Pressable>
          </Link>
        )}
        keyExtractor={(item) => item.id.toString()}
        ItemSeparatorComponent={() => <Separator borderColor="$borderColor" />}
        showsVerticalScrollIndicator={false}
        onEndReached={() => {
          if (hasPreviousPage && !isFetchingPreviousPage) fetchPreviousPage()
        }}
        onEndReachedThreshold={0.5}
        ListFooterComponent={<ListFooter loading={isFetchingPreviousPage} />}
      />
    </SafeAreaView>
  )
}
