import {useEffect} from 'react'

import {CrumbPreviewCard} from '@/components/home/crumb-preview-card'
import {SeeAllLink} from '@/components/see-all-link'
import {Carousel} from '@/components/ui/carousel'
import {Tile} from '@/components/ui/tile'
import {Text} from '@/components/ui/typography'
import type {Coords} from '@/hooks/use-current-location'
import {useFriendRecs} from '@/hooks/use-friend-recs'
import {formatDistanceKm} from '@/lib/geo'
import {useTheme} from '@/sprinkles'

export const FriendRecsTile = ({center}: {center: Coords}) => {
  const t = useTheme()
  const {recs, loading, fetch, reset} = useFriendRecs()

  useEffect(() => {
    void fetch({lat: center.latitude, lng: center.longitude})
    return reset
  }, [fetch, reset, center.latitude, center.longitude])

  return (
    <Tile
      label="Popular with friends"
      action={
        <SeeAllLink
          href={{
            pathname: '/friend-recs',
            params: {
              lat: String(center.latitude),
              lng: String(center.longitude),
            },
          }}
          label="See all popular crumbs"
        />
      }
    >
      {recs.length === 0 ? (
        // errors land here too: a glanceable tile stays quiet over loud
        <Text style={t.atoms.text_contrast_medium}>
          {loading
            ? 'Finding picks nearby…'
            : 'No friend picks nearby yet'}
        </Text>
      ) : (
        <Carousel>
          {recs.map((rec) => (
            <CrumbPreviewCard
              key={rec.crumb.id}
              crumb={rec.crumb}
              author={rec.author}
              reactions={rec.reactions}
              meta={formatDistanceKm(rec.distanceKm)}
            />
          ))}
        </Carousel>
      )}
    </Tile>
  )
}
