import { FlashList } from '@shopify/flash-list'
import { useQuery } from '@tanstack/react-query'
import type { ErrorBoundaryProps } from 'expo-router'
import { Link } from 'expo-router'
import { useMemo } from 'react'
import { SafeAreaView } from 'react-native-safe-area-context'
import { EmptyState } from 'src/components/common/EmptyState'
import { ErrorState } from 'src/components/common/ErrorState'
import { LoadingView } from 'src/components/common/LoadingView'
import { useScreenMenu, useSearchQuery } from 'src/components/menu'
import { hashtagQueries } from 'src/lib/queries/hashtags'
import { Separator, Text, View } from 'tamagui'

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

export default function Screen() {
  const { data: feed, isPending, error, refetch } = useQuery(hashtagQueries.followed())
  const [query, setQuery] = useSearchQuery()
  useScreenMenu({
    title: 'Followed Hashtags',
    intents: [
      {
        kind: 'search',
        placeholder: 'Filter hashtags',
        value: query,
        onChangeText: setQuery,
      },
    ],
  })

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase()
    if (!q || !Array.isArray(feed)) return feed
    return feed.filter((tag: any) => tag?.name?.toLowerCase().includes(q))
  }, [feed, query])

  if (isPending) return <LoadingView />
  if (error) return <ErrorState onRetry={refetch} />

  return (
    <SafeAreaView style={{ flex: 1 }} edges={['top', 'bottom']}>
      <FlashList
        data={filtered}
        renderItem={({ item }: { item: any }) => (
          <Link href={`/hashtag/${item.name}`} asChild>
            <View p="$5" bg="$backgroundSecondary">
              <Text fontSize="$6" color="$color">
                #{item.name}
              </Text>
            </View>
          </Link>
        )}
        ItemSeparatorComponent={() => <Separator borderColor="$borderColor" />}
        ListEmptyComponent={
          <EmptyState icon="alert-circle" title="Not following any hashtags" />
        }
        contentContainerStyle={{ flexGrow: 1 }}
      />
    </SafeAreaView>
  )
}
