import {TagNameSchema} from '@crumbs/core/schemas'
import {useState} from 'react'
import {View} from 'react-native'

import {Chip} from '@/components/chip'
import {FormField} from '@/components/forms/form-field'
import * as TextField from '@/components/forms/text-field'
import {Text} from '@/components/ui/typography'
import {atoms as a, useTheme} from '@/sprinkles'

// the tag section of the composer: suggestions, the selected set, and a
// free-form add input (owns its own input state)
export const TagPicker = ({
  suggestions,
  loading,
  error,
  selected,
  onToggle,
  onAdd,
  disabled,
}: {
  suggestions: {name: string}[]
  loading: boolean
  error: string | null
  selected: string[]
  onToggle: (name: string) => void
  onAdd: (name: string) => void
  disabled?: boolean
}) => {
  const t = useTheme()
  const [input, setInput] = useState('')

  const tryAddInput = () => {
    const parsed = TagNameSchema.safeParse(input)
    if (!parsed.success) return
    onAdd(parsed.data)
    setInput('')
  }

  return (
    <>
      <FormField label="Suggestions">
        {loading ? (
          <Text style={t.atoms.text_contrast_medium}>Loading…</Text>
        ) : error ? (
          <Text style={t.atoms.text_contrast_medium}>{error}</Text>
        ) : suggestions.length === 0 ? (
          <Text style={t.atoms.text_contrast_medium}>
            None yet — add one below
          </Text>
        ) : (
          <View style={[a.flex_row, a.flex_wrap, a.gap_sm]}>
            {suggestions.map((s) => (
              <Chip
                key={s.name}
                label={s.name}
                selected={selected.includes(s.name)}
                onPress={() => onToggle(s.name)}
              />
            ))}
          </View>
        )}
      </FormField>

      {selected.length > 0 && (
        <FormField label="Selected">
          <View style={[a.flex_row, a.flex_wrap, a.gap_sm]}>
            {selected.map((name) => (
              <Chip
                key={name}
                label={name}
                selected
                onPress={() => onToggle(name)}
              />
            ))}
          </View>
        </FormField>
      )}

      <FormField label="Add tag">
        <TextField.Input
          label="Add tag"
          value={input}
          onChangeText={setInput}
          onSubmitEditing={tryAddInput}
          placeholder="e.g. Coffee"
          autoCapitalize="none"
          autoCorrect={false}
          returnKeyType="done"
          editable={!disabled}
        />
      </FormField>
    </>
  )
}
