import React, { forwardRef } from "react";
import {
  KeyboardTypeOptions,
  NativeSyntheticEvent,
  TextInput as RNTextInput,
  TextInputContentSizeChangeEventData,
  TextInputProps,
  ViewStyle,
} from "react-native";

import styledComponent from "../../utils/styledComponent";
import { View } from "../View";
import styles from "./styles";

export type InputProps = {
  autoFocus?: boolean;
  icon?: React.ReactNode;
  onBlur?: () => void;
  onChange?: (value: string) => void;
  onContentSizeChange?: (
    e: NativeSyntheticEvent<TextInputContentSizeChangeEventData>
  ) => void;
  onFocus?: () => void;
  placeholder?: string;
  value?: string | number;
  keyboardType?: KeyboardTypeOptions;
  multiline?: boolean;
  secureTextEntry?: boolean;
  style?: ViewStyle;
  dark?: boolean;
  disabled?: boolean;
};

const StyledTextInput = styledComponent<TextInputProps>(RNTextInput);

const Input = forwardRef<typeof StyledTextInput, InputProps>(
  (
    { icon, value, onChange, style, dark, disabled, ...props }: InputProps,
    forwardedRef
  ) => {
    const input = (
      <StyledTextInput
        {...props}
        onChangeText={onChange}
        value={value == null ? "" : String(value)}
        style={[
          styles.input,
          dark && styles.darkInput,
          disabled && (dark ? styles.disabledDark : styles.disabled),
          style,
        ]}
        editable={!disabled}
        ref={forwardedRef}
      />
    );
    return icon ? (
      <View>
        {input}
        <View style={[styles.iconContainer, dark && styles.darkIconContainer]}>
          {icon}
        </View>
      </View>
    ) : (
      input
    );
  }
);

export default Input;
