/** Text input with label, error line, optional secure toggle & leading icon. */
import React, {useState} from 'react';
import {StyleSheet, Text, TextInput, TouchableOpacity, View, ViewStyle} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import {COLORS} from '../theme/colors';
import {RADIUS, SPACING} from '../theme/spacing';

interface Props {
  label?: string;
  value: string;
  onChangeText: (v: string) => void;
  placeholder?: string;
  secure?: boolean;
  error?: string | null;
  keyboardType?: 'default' | 'email-address' | 'numeric' | 'phone-pad';
  icon?: string; // Ionicons name
  multiline?: boolean;
  autoCapitalize?: 'none' | 'sentences' | 'words' | 'characters';
  style?: ViewStyle;
  maxLength?: number;
  editable?: boolean;
}

export function Input({
  label,
  value,
  onChangeText,
  placeholder,
  secure,
  error,
  keyboardType = 'default',
  icon,
  multiline,
  autoCapitalize = 'none',
  style,
  maxLength,
  editable = true,
}: Props): React.JSX.Element {
  const [show, setShow] = useState(false);
  const isSecure = secure && !show;

  return (
    <View style={[styles.wrap, style]}>
      {label ? <Text style={styles.label}>{label}</Text> : null}
      <View style={[styles.field, !!error && styles.fieldError, multiline && styles.multiline]}>
        {icon ? <Icon name={icon} size={18} color={COLORS.secondaryText} style={styles.icon} /> : null}
        <TextInput
          style={[styles.input, multiline && styles.inputMultiline]}
          value={value}
          onChangeText={onChangeText}
          placeholder={placeholder}
          placeholderTextColor={COLORS.secondaryText}
          secureTextEntry={isSecure}
          keyboardType={keyboardType}
          autoCapitalize={autoCapitalize}
          autoCorrect={!secure}
          multiline={multiline}
          maxLength={maxLength}
          editable={editable}
        />
        {secure ? (
          <TouchableOpacity onPress={() => setShow(s => !s)} hitSlop={10}>
            <Icon name={show ? 'eye-off-outline' : 'eye-outline'} size={20} color={COLORS.secondaryText} />
          </TouchableOpacity>
        ) : null}
      </View>
      {error ? <Text style={styles.error}>{error}</Text> : null}
    </View>
  );
}

const styles = StyleSheet.create({
  wrap: {marginBottom: SPACING.l},
  label: {color: COLORS.secondaryText, fontSize: 13, marginBottom: 6, fontWeight: '600'},
  field: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: COLORS.inputBg,
    borderRadius: RADIUS.m,
    borderWidth: 1,
    borderColor: 'transparent',
    paddingHorizontal: SPACING.l,
  },
  fieldError: {borderColor: COLORS.danger},
  multiline: {minHeight: 96, alignItems: 'flex-start', paddingVertical: SPACING.m},
  icon: {marginRight: 10},
  input: {flex: 1, color: COLORS.white, fontSize: 15, paddingVertical: 13},
  inputMultiline: {textAlignVertical: 'top'},
  error: {color: COLORS.danger, fontSize: 12, marginTop: 5},
});
