import {useLocalSearchParams, useRouter} from 'expo-router'
import {View} from 'react-native'

import {Chip} from '@/components/chip'
import {CrumbList} from '@/components/crumb-list'
import {ModalListScreen} from '@/components/modal-list-screen'
import {usePagedListScreen} from '@/hooks/use-paged-list-screen'
import {decodeFilter, matchesFilter} from '@/lib/map'
import {atoms as a} from '@/sprinkles'
import {useAuth} from '@/stores/auth'
import {placeCrumbs} from '@/stores/place-crumbs'

export default function PlaceCrumbsScreen() {
  const {placeId, f} = useLocalSearchParams<{
    placeId: string
    f?: string
  }>()
  const router = useRouter()
  const user = useAuth((s) => s.user)
  const filter = decodeFilter(f)
  // refetch on focus so edits made in a pushed detail screen show on return
  const {items, loading, loadingMore, screenProps} =
    usePagedListScreen(placeCrumbs, placeId, {refetchOnFocus: true})

  const crumbs = items.filter((c) => matchesFilter(c, filter))
  const title = items[0]?.place?.name ?? 'Place'

  return (
    <ModalListScreen
      title={title}
      {...screenProps}
      itemCount={crumbs.length}
    >
      {filter.kind !== 'all' && (
        <View style={[a.flex_row, a.py_sm]}>
          <Chip
            label={
              filter.kind === 'tag'
                ? `${filter.tag} ×`
                : `${filter.status} ×`
            }
            selected
            onPress={() => router.setParams({f: undefined})}
          />
        </View>
      )}
      <CrumbList
        crumbs={crumbs}
        showAuthor
        currentUserId={user?.id}
        loading={loading}
        loadingMore={loadingMore}
        emptyMessage="No crumbs here"
      />
    </ModalListScreen>
  )
}
