import { Feather } from '@expo/vector-icons'
import { FlashList } from '@shopify/flash-list'
import { useQuery } from '@tanstack/react-query'
import type { ErrorBoundaryProps } from 'expo-router'
import { useCallback } from 'react'
import { ActivityIndicator } from 'react-native'
import { ErrorState } from 'src/components/common/ErrorState'
import { ScreenScrollContainer } from 'src/components/layout'
import { useFilteredList, useScreenMenu, useSearchQuery } from 'src/components/menu'
import { ICON } from 'src/lib/icons'
import { privacyQueries } from 'src/lib/queries/privacy'
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 RenderItem = ({ item }: { item: any }) => {
    return (
      <XStack
        p="$5"
        bg={theme.backgroundSecondary.val}
        alignItems="center"
        gap="$3"
        flexWrap="wrap"
      >
        <Text fontSize="$6" fontWeight={'bold'} flexWrap="wrap" color={theme.color.val}>
          {item}
        </Text>
      </XStack>
    )
  }

  const RenderSeparator = () => <Separator borderColor={theme.borderColor.val} />

  const RenderEmpty = () => (
    <View flexGrow={1} justifyContent="center" alignItems="center" py="$5">
      <YStack flexShrink={1} justifyContent="center" alignItems="center" gap="$5">
        <Feather name="alert-circle" size={ICON.empty} color={theme.colorTertiary.val} />
        <Text fontSize="$7" allowFontScaling={false} color={theme.color.val}>
          You are not blocking any domains
        </Text>
      </YStack>
    </View>
  )

  const RenderLoading = () => (
    <View flexGrow={1} justifyContent="center" alignItems="center" py="$5">
      <YStack flexShrink={1} justifyContent="center" alignItems="center">
        <ActivityIndicator size="large" color={theme.color.val} />
      </YStack>
    </View>
  )

  const [query, setQuery] = useSearchQuery()
  useScreenMenu({
    title: 'Blocked Domains',
    intents: [
      {
        kind: 'search',
        placeholder: 'Filter domains',
        value: query,
        onChangeText: setQuery,
      },
    ],
  })
  const { isPending, data } = useQuery(privacyQueries.blockedDomains())

  const filteredData = useFilteredList<string>(
    Array.isArray(data) ? (data as string[]) : [],
    query,
    useCallback((domain: string) => [domain], [])
  )

  return (
    <ScreenScrollContainer variant="flashlist">
      {(scrollProps) => (
        <FlashList
          data={filteredData}
          renderItem={RenderItem}
          ItemSeparatorComponent={RenderSeparator}
          ListEmptyComponent={isPending ? RenderLoading : RenderEmpty}
          ListHeaderComponent={
            <View p="$5">
              <Text color={theme.colorSecondary.val}>
                To add or delete blocked domains, navigate to Privacy Settings from a web
                browser.
              </Text>
            </View>
          }
          contentInsetAdjustmentBehavior={scrollProps.contentInsetAdjustmentBehavior}
          contentInset={scrollProps.contentInset}
          scrollIndicatorInsets={scrollProps.scrollIndicatorInsets}
          contentContainerStyle={{
            ...scrollProps.contentContainerStyle,
            flexGrow: 1,
          }}
        />
      )}
    </ScreenScrollContainer>
  )
}
