import { FlashList } from '@shopify/flash-list'
import { useInfiniteQuery } from '@tanstack/react-query'
import { type ErrorBoundaryProps, 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 { ListFooter } from 'src/components/common/ListFooter'
import { LoadingView } from 'src/components/common/LoadingView'
import ImageComponent from 'src/components/ImageComponent'
import { useScreenMenu, useSearchQuery } from 'src/components/menu'
import { useRequirePixelfed } from 'src/hooks/useRequirePixelfed'
import { toImageUri } from 'src/lib/media-source'
import { collectionQueries } from 'src/lib/queries/collections'
import { formatTimestamp } from 'src/utils'
import { ScrollView, Text, View, XStack, YStack } from 'tamagui'

const RenderItem = ({ item }: { item: any }) => (
  <YStack px="$5" mb="$5">
    <YStack pt="$5" pb="$3" borderTopLeftRadius={20} borderTopRightRadius={20} gap="$1">
      <Text fontWeight="bold" fontSize="$8">
        {item.title ? item.title : 'Untitled Collection'}
        {item.items && item.items.length > 6 ? ` (${item.items.length})` : null}
      </Text>
      <XStack justifyContent="space-between" flexWrap="wrap" flexShrink={1} gap="$2">
        <Text fontSize="$4" color="$colorTertiary" flexWrap="wrap">
          {item.description ? item.description : 'No description'}
        </Text>
        <Text fontSize="$4" color="$colorTertiary">
          {formatTimestamp(item.updated_at)}
        </Text>
      </XStack>
    </YStack>
    {item.post_count === 0 || !item.items.length ? (
      <YStack
        bg="$background"
        p="$5"
        borderWidth={1}
        borderColor="$borderColor"
        borderRadius={20}
        borderCurve="continuous"
      >
        <Text textAlign="center" fontWeight="bold">
          Empty collection
        </Text>
      </YStack>
    ) : (
      <YStack
        borderWidth={1}
        borderColor="$borderColor"
        borderRadius={20}
        borderCurve="continuous"
      >
        <ScrollView horizontal showsHorizontalScrollIndicator={false}>
          {item.items.map((post: any) => (
            <Link key={post.id} href={`/post/${post.id}`} asChild>
              <View>
                <ImageComponent
                  source={{ uri: toImageUri(post.media_attachments[0]) }}
                  style={{
                    width: 100,
                    height: 100,
                    borderRadius: 10,
                    marginRight: 10,
                  }}
                  resizeMode={'cover' as any}
                />
              </View>
            </Link>
          ))}
        </ScrollView>
      </YStack>
    )}
  </YStack>
)

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

export default function Screen() {
  // Mastodon Pass Phase 4 §5.3 — Collections (`api/v1.1/collections/*`)
  // are Pixelfed-only; redirect Mastodon-active sessions away.
  useRequirePixelfed()
  const [query, setQuery] = useSearchQuery()
  useScreenMenu({
    title: 'Collections',
    intents: [
      {
        kind: 'search',
        placeholder: 'Filter collections',
        value: query,
        onChangeText: setQuery,
      },
    ],
  })
  const {
    data: collections,
    error,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    status,
    refetch,
  } = useInfiniteQuery(collectionQueries.self())

  const flattenedData = useMemo(() => {
    const flat = collections?.pages.flat() ?? []
    const q = query.trim().toLowerCase()
    if (!q) return flat
    return flat.filter((c: any) => {
      const title = c?.title?.toLowerCase() ?? ''
      const description = c?.description?.toLowerCase() ?? ''
      return title.includes(q) || description.includes(q)
    })
  }, [collections?.pages, query])

  if (status === 'pending') return <LoadingView />
  if (status === 'error') return <ErrorState message={error.message} onRetry={refetch} />

  return (
    <SafeAreaView style={{ flex: 1 }} edges={['top', 'bottom']}>
      <FlashList
        data={flattenedData}
        renderItem={RenderItem}
        ItemSeparatorComponent={() => <View h={10} />}
        ListEmptyComponent={<EmptyState icon="inbox" title="No collections found" />}
        contentContainerStyle={{ flexGrow: 1 }}
        onEndReached={() => {
          if (hasNextPage && !isFetchingNextPage) fetchNextPage()
        }}
        ListFooterComponent={<ListFooter loading={isFetchingNextPage} />}
      />
    </SafeAreaView>
  )
}
