import { ComponentProps } from "react";
import { Controller } from "react-hook-form";
import { View } from "react-native";
import ErrorText from "./error-text";
import { Input, InputField } from "./input";
import { ThemedText } from "./themed-text";

interface FormInputProps {
  name: string;
  control: any;
  label?: string;
  className?: string;
  inputProps?: ComponentProps<typeof Input>;
  fieldProps?: ComponentProps<typeof InputField>;
}

const FormInput = ({
  name,
  control,
  inputProps,
  fieldProps,
  label,
  className,
}: FormInputProps) => {
  return (
    <View className={className}>
      <Controller
        name={name}
        control={control}
        render={(renderProps) => (
          <View>
            {label && (
              <ThemedText className="font-semibold mb-1">{label}</ThemedText>
            )}
            <Input isInvalid={!!renderProps.fieldState.error} {...inputProps}>
              <InputField
                onChangeText={renderProps.field.onChange}
                value={renderProps.field.value}
                {...fieldProps}
              />
            </Input>
            {!!renderProps.fieldState.error && (
              <ErrorText>{renderProps.fieldState.error.message}</ErrorText>
            )}
          </View>
        )}
      />
    </View>
  );
};

export default FormInput;
