import {useEffect} from 'react'

import {Attribution} from '@/components/attribution'
import {ErrorState} from '@/components/error-state'
import {ModalListScreen} from '@/components/modal-list-screen'
import {Button} from '@/components/ui/button'
import {CardRow, CardRowTitle} from '@/components/ui/card'
import {List} from '@/components/ui/list'
import {PressableRow} from '@/components/ui/pressable-row'
import {Text} from '@/components/ui/typography'
import {useCrumbComposer} from '@/hooks/use-crumb-composer'
import {useNearbyPlaces} from '@/hooks/use-nearby-places'
import {atoms as a, useTheme} from '@/sprinkles'

export default function NearbyScreen() {
  const t = useTheme()
  const {pickPlace, composeNote} = useCrumbComposer()
  const {loading, error, places, fetch, reset} = useNearbyPlaces()

  useEffect(() => {
    void fetch()
    return reset
  }, [fetch, reset])

  const footer = (
    <>
      <Attribution style={a.mt_md} />
      {/* always available: skip the place and save a plain note */}
      <Button
        label="Add without a place"
        variant="ghost"
        color="primary"
        size="large"
        shape="rectangular"
        onPress={composeNote}
        style={a.mt_lg}
      />
    </>
  )

  return (
    <ModalListScreen title="Nearby" footer={footer}>
      {error ? (
        <ErrorState message={error} onRetry={() => void fetch()} />
      ) : (
        <List
          items={places}
          loading={loading}
          emptyMessage="No nearby places found"
          renderItem={(item) => (
            <PressableRow
              accessibilityLabel={item.name}
              onPress={() => pickPlace(item)}
            >
              <CardRow>
                <CardRowTitle>{item.name}</CardRowTitle>
                {item.address && (
                  <Text style={[t.atoms.text_contrast_medium]}>
                    {item.address}
                  </Text>
                )}
              </CardRow>
            </PressableRow>
          )}
        />
      )}
    </ModalListScreen>
  )
}
