import { FlashList } from '@shopify/flash-list'
import { useQuery } from '@tanstack/react-query'
import { type ErrorBoundaryProps, Link } from 'expo-router'
import { useCallback } from 'react'
import { EmptyState } from 'src/components/common/EmptyState'
import { ErrorState } from 'src/components/common/ErrorState'
import { LoadingView } from 'src/components/common/LoadingView'
import { UserRow } from 'src/components/common/UserRow'
import { ScreenScrollContainer } from 'src/components/layout'
import { useFilteredList, useScreenMenu, useSearchQuery } from 'src/components/menu'
import { privacyQueries } from 'src/lib/queries/privacy'
import { Separator } from 'tamagui'

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

type Account = { id: string; acct?: string; display_name?: string }

export default function Page() {
  const [query, setQuery] = useSearchQuery()
  useScreenMenu({
    title: 'Muted Accounts',
    intents: [
      {
        kind: 'search',
        placeholder: 'Filter muted accounts',
        value: query,
        onChangeText: setQuery,
      },
    ],
  })
  const { isPending, data } = useQuery(privacyQueries.mutedAccounts())

  const filteredData = useFilteredList<Account>(
    Array.isArray(data) ? (data as Account[]) : [],
    query,
    useCallback((item: Account) => [item.acct, item.display_name], [])
  )

  return (
    <ScreenScrollContainer variant="flashlist">
      {(scrollProps) => (
        <FlashList
          data={filteredData}
          renderItem={({ item }: { item: any }) => (
            <Link href={`/profile/${item.id}`} asChild>
              <UserRow account={item} />
            </Link>
          )}
          ItemSeparatorComponent={() => <Separator borderColor="$borderColor" />}
          ListEmptyComponent={
            isPending ? (
              <LoadingView />
            ) : (
              <EmptyState icon="alert-circle" title="No results found" />
            )
          }
          contentInsetAdjustmentBehavior={scrollProps.contentInsetAdjustmentBehavior}
          contentInset={scrollProps.contentInset}
          scrollIndicatorInsets={scrollProps.scrollIndicatorInsets}
          contentContainerStyle={{
            ...scrollProps.contentContainerStyle,
            flexGrow: 1,
          }}
        />
      )}
    </ScreenScrollContainer>
  )
}
