import {View} from 'react-native'

import {Avatar} from '@/components/ui/avatar'
import {Card, CardRow, CardRowTitle} from '@/components/ui/card'
import {PressableRow} from '@/components/ui/pressable-row'
import {atoms as a} from '@/sprinkles'

const MAX_SUGGESTIONS = 5

export type MentionCandidate = {
  id: string
  handle: string
  avatarUrl: string | null
}

// suggestions for the @mention token under the cursor; candidates are the
// trail's members, so a plain prefix filter beats any search endpoint
export const MentionAutocomplete = ({
  prefix,
  candidates,
  onSelect,
}: {
  prefix: string
  candidates: MentionCandidate[]
  onSelect: (handle: string) => void
}) => {
  const query = prefix.toLowerCase()
  const matches = candidates
    .filter((c) => c.handle.toLowerCase().startsWith(query))
    .slice(0, MAX_SUGGESTIONS)
  if (matches.length === 0) return null

  return (
    <Card>
      {matches.map((candidate) => (
        <PressableRow
          key={candidate.id}
          accessibilityLabel={`Mention @${candidate.handle}`}
          onPress={() => onSelect(candidate.handle)}
        >
          <CardRow trailing={null} style={a.py_sm}>
            <View style={[a.flex_row, a.align_center, a.gap_sm]}>
              <Avatar
                handle={candidate.handle}
                uri={candidate.avatarUrl}
                size={28}
              />
              <CardRowTitle>@{candidate.handle}</CardRowTitle>
            </View>
          </CardRow>
        </PressableRow>
      ))}
    </Card>
  )
}
