import {type ReactNode} from 'react'
import {TextInput, type TextInputProps} from 'react-native'

import {MAX_FONT_SCALE} from '@/components/ui/typography'
import {atoms as a, useTheme} from '@/sprinkles'

type ComposerTextInputProps = {
  value: string
  onChangeText: (v: string) => void
  placeholder?: string
  maxLength: number
  autoFocus?: boolean
  multiline?: boolean
  autoCapitalize?: TextInputProps['autoCapitalize']
  autoCorrect?: boolean
  returnKeyType?: TextInputProps['returnKeyType']
  onSelectionChange?: TextInputProps['onSelectionChange']
  // styled segments rendered instead of the plain value (mention
  // highlighting); rn forbids passing value alongside children
  children?: ReactNode
}

export const ComposerTextInput = ({
  value,
  onChangeText,
  placeholder,
  maxLength,
  autoFocus,
  multiline = true,
  autoCapitalize,
  autoCorrect,
  returnKeyType,
  onSelectionChange,
  children,
}: ComposerTextInputProps) => {
  const t = useTheme()

  return (
    <TextInput
      {...(children ? {} : {value})}
      maxFontSizeMultiplier={MAX_FONT_SCALE}
      onChangeText={onChangeText}
      placeholder={placeholder}
      placeholderTextColor={t.atoms.text_contrast_medium.color}
      maxLength={maxLength}
      autoFocus={autoFocus}
      multiline={multiline}
      scrollEnabled={false}
      autoCapitalize={autoCapitalize}
      autoCorrect={autoCorrect}
      returnKeyType={returnKeyType}
      onSelectionChange={onSelectionChange}
      style={[
        a.text_xl,
        t.atoms.text,
        {
          lineHeight: 28,
          minHeight: 60,
          textAlignVertical: 'top',
          includeFontPadding: false,
        },
      ]}
    >
      {children}
    </TextInput>
  )
}
