import { FlashList } from '@shopify/flash-list'
import { useQuery } from '@tanstack/react-query'
import type { ErrorBoundaryProps } from 'expo-router'
import { useCallback, useState } 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 {
  ConfirmDialog,
  useFilteredList,
  useScreenMenu,
  useSearchQuery,
} from 'src/components/menu'
import { unblockProfileById } from 'src/lib/api'
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
  avatar: string
}

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

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

  const [pending, setPending] = useState<Account | null>(null)

  const unblock = async () => {
    if (!pending) return
    await unblockProfileById(pending.id)
    await refetchBlocks({ throwOnError: true })
  }

  return (
    <ScreenScrollContainer variant="flashlist">
      {(scrollProps) => (
        <>
          <FlashList
            data={filteredData}
            renderItem={({ item }: { item: Account }) => (
              <UserRow account={item} onPress={() => setPending(item)} />
            )}
            ItemSeparatorComponent={() => <Separator borderColor="$borderColor" />}
            ListEmptyComponent={
              isPending ? (
                <LoadingView />
              ) : (
                <EmptyState
                  icon="alert-circle"
                  title="You are not blocking any accounts"
                />
              )
            }
            contentInsetAdjustmentBehavior={scrollProps.contentInsetAdjustmentBehavior}
            contentInset={scrollProps.contentInset}
            scrollIndicatorInsets={scrollProps.scrollIndicatorInsets}
            contentContainerStyle={{
              ...scrollProps.contentContainerStyle,
              flexGrow: 1,
            }}
          />
          <ConfirmDialog
            open={!!pending}
            onOpenChange={(open) => {
              if (!open) setPending(null)
            }}
            title="Unblock User"
            message={pending ? `Do you really want to unblock ${pending.acct}?` : ''}
            confirmLabel="Unblock"
            destructive
            onConfirm={unblock}
          />
        </>
      )}
    </ScreenScrollContainer>
  )
}
