import type { ComponentProps } from 'react'
import { useId } from 'react'
import { Input, Label, TextArea, useTheme, XStack, YStack } from 'tamagui'
import { CharCountText } from './CharCount'
import { FieldErrorText, FieldHelperText } from './FieldText'

// Standard label / input / helper / error layout for inline form fields. The
// `htmlFor` ↔ `id` association is what gives screen readers the label →
// field link on web and the same TalkBack/VoiceOver pairing on native, so
// every consumer gets a11y for free instead of having to remember to wire
// it up. Picks `Input` vs `TextArea` from `multiline`. Mirrors the geometry
// the routed `ProfileFieldEditor` open-coded — char count on the right of
// the label baseline, helper text below, error text below that.

type FormFieldProps = {
  label: string
  helper?: string
  error?: string
  maxLength?: number
  multiline?: boolean
  // Pull the value out of the input prop bag explicitly so we can render the
  // char counter without having to inspect the same value twice at call
  // sites.
  value?: string
  onChangeText?: (next: string) => void
} & Omit<ComponentProps<typeof Input>, 'onChangeText' | 'value'>

export function FormField({
  label,
  helper,
  error,
  maxLength,
  multiline,
  value,
  onChangeText,
  ...inputProps
}: FormFieldProps) {
  const id = useId()
  const theme = useTheme()
  const length = value?.length ?? 0
  const inputCommon = {
    id,
    value,
    onChangeText,
    maxLength,
    bg: theme.backgroundTertiary.val,
    borderColor: theme.borderColor.val,
    color: theme.color.val,
    placeholderTextColor: theme.colorTertiary.val as any,
    size: '$5' as const,
  }
  return (
    <YStack gap="$2">
      <XStack alignItems="baseline" justifyContent="space-between">
        <Label htmlFor={id} fontSize="$label" color="$colorTertiary">
          {label}
        </Label>
        {maxLength ? (
          <CharCountText>
            {length}/{maxLength}
          </CharCountText>
        ) : null}
      </XStack>
      {multiline ? (
        <TextArea
          numberOfLines={6}
          {...inputCommon}
          {...(inputProps as ComponentProps<typeof TextArea>)}
        />
      ) : (
        <Input {...inputCommon} {...(inputProps as ComponentProps<typeof Input>)} />
      )}
      {helper ? <FieldHelperText>{helper}</FieldHelperText> : null}
      {error ? <FieldErrorText>{error}</FieldErrorText> : null}
    </YStack>
  )
}
