import {useLocalSearchParams} from 'expo-router'
import {useEffect} from 'react'

import {
  CrumbList,
  type CrumbWithAuthor,
} from '@/components/crumb-list'
import {ErrorState} from '@/components/error-state'
import {ModalListScreen} from '@/components/modal-list-screen'
import {useFriendRecs} from '@/hooks/use-friend-recs'
import {parseCoordParams} from '@/lib/geo'

export default function FriendRecsScreen() {
  const {lat, lng} = useLocalSearchParams<{
    lat: string
    lng: string
  }>()
  const {recs, loading, error, fetch, reset} = useFriendRecs()
  const coords = parseCoordParams(lat, lng)
  const {latitude, longitude} = coords ?? {}

  useEffect(() => {
    if (latitude != null && longitude != null)
      void fetch({lat: latitude, lng: longitude})
    return reset
  }, [fetch, reset, latitude, longitude])

  const crumbs: CrumbWithAuthor[] = recs.map((rec) => ({
    ...rec.crumb,
    authorHandle: rec.author.handle,
    reactions: rec.reactions,
  }))

  return (
    <ModalListScreen title="Popular with friends">
      {error ? (
        <ErrorState
          message={error}
          onRetry={() =>
            coords &&
            void fetch({lat: coords.latitude, lng: coords.longitude})
          }
        />
      ) : (
        <CrumbList
          crumbs={crumbs}
          loading={loading}
          emptyMessage="No friend picks nearby yet"
          showAuthor
        />
      )}
    </ModalListScreen>
  )
}
