import { FlashList } from '@shopify/flash-list'
import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query'
import { type ErrorBoundaryProps, Link } from 'expo-router'
import { useMemo } from 'react'
import { Pressable, RefreshControl } from 'react-native'
import { EmptyState } from 'src/components/common/EmptyState'
import { ErrorState } from 'src/components/common/ErrorState'
import { ListFooter } from 'src/components/common/ListFooter'
import { LoadingView } from 'src/components/common/LoadingView'
import UserAvatar from 'src/components/common/UserAvatar'
import {
  ScreenScrollContainer,
  useAccentRefreshControlProps,
} from 'src/components/layout'
import { useScreenMenu, useSearchQuery } from 'src/components/menu'
import { haptic } from 'src/lib/haptics'
import { notificationQueries } from 'src/lib/queries/notifications'
import { enforceLen, 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} />
}

export default function Page() {
  const theme = useTheme()
  const queryClient = useQueryClient()
  const refreshProps = useAccentRefreshControlProps()
  const [query, setQuery] = useSearchQuery()
  useScreenMenu({
    title: 'Filtered Requests',
    intents: [
      {
        kind: 'search',
        placeholder: 'Filter requests',
        value: query,
        onChangeText: setQuery,
      },
    ],
  })

  const {
    data,
    error,
    isFetching,
    isFetchingNextPage,
    isRefetching,
    hasNextPage,
    fetchNextPage,
    refetch,
  } = useInfiniteQuery(notificationQueries.requests())

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

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

  const handleInfinite = () => {
    if (isFetchingNextPage) return
    if (hasNextPage) fetchNextPage()
  }

  return (
    <ScreenScrollContainer variant="flashlist">
      {(scrollProps) => (
        <FlashList
          data={flattened}
          ItemSeparatorComponent={() => <Separator borderColor={theme.borderColor.val} />}
          keyExtractor={(item: any, index) => `${item?.id ?? index}_${index}`}
          onEndReached={handleInfinite}
          onEndReachedThreshold={0.5}
          refreshControl={
            <RefreshControl
              refreshing={isRefetching}
              onRefresh={() =>
                queryClient
                  .invalidateQueries({
                    queryKey: notificationQueries.requests().queryKey,
                  })
                  .then(() => haptic.light())
              }
              progressViewOffset={scrollProps.topInset}
              {...refreshProps}
            />
          }
          ListEmptyComponent={
            <EmptyState
              icon="inbox"
              title="No filtered requests"
              subtitle="Notifications filtered by your policy will appear here."
            />
          }
          ListFooterComponent={
            <View py="$6">
              <ListFooter loading={isFetchingNextPage} />
            </View>
          }
          contentInsetAdjustmentBehavior={scrollProps.contentInsetAdjustmentBehavior}
          contentInset={scrollProps.contentInset}
          scrollIndicatorInsets={scrollProps.scrollIndicatorInsets}
          contentContainerStyle={scrollProps.contentContainerStyle}
          renderItem={({ item }: { item: any }) => {
            const account = item?.account
            return (
              <View px="$4" py="$3">
                <XStack gap="$3" alignItems="center">
                  {account?.id ? (
                    <Link href={`/profile/${account.id}`} asChild>
                      <Pressable>
                        <Link.Trigger>
                          <UserAvatar url={account.avatar} />
                        </Link.Trigger>
                        <Link.Preview style={{ width: 320, height: 420 }} />
                      </Pressable>
                    </Link>
                  ) : null}
                  <YStack flexShrink={1} gap="$1">
                    <Text fontSize="$3" fontWeight="bold" color={theme.color.val}>
                      @{enforceLen(account?.acct ?? 'unknown', 30, true)}
                    </Text>
                    <Text fontSize="$2" color={theme.colorSecondary.val}>
                      {item?.notifications_count ?? 1} filtered notification
                      {(item?.notifications_count ?? 1) === 1 ? '' : 's'}
                    </Text>
                    {item?.last_status?.created_at ? (
                      <Text fontSize="$2" color={theme.colorTertiary.val}>
                        {timeAgo(item.last_status.created_at)}
                      </Text>
                    ) : null}
                  </YStack>
                </XStack>
              </View>
            )
          }}
        />
      )}
    </ScreenScrollContainer>
  )
}
