import React from "react";
import { View, ViewProps } from "react-native";
import { isEmail } from "validator";
import { EMPTY_FIELD, INVALID_EMAIL, NOT_MATCHING_PASSWORD } from "../Errors";
import Button from "../ui/Button";
import FormError from "./FormError";
import TextInput from "./FormInput";
import PasswordTextInput from "./SecretTextInput";

export default React.forwardRef<any, ViewProps>(
  ({ ...props }, ref): React.ReactElement => {
    const [email, setEmail] = React.useState("");
    const [password, setPassword] = React.useState("");
    const [confirmPassword, setConfirmPassword] = React.useState("");
    const [error, setError] = React.useState("");
    const [isFormValid, setIsFormValid] = React.useState(true);

    const validateForm = () => {
      setError("");
      setIsFormValid(true);
    };

    const invalidateForm = (error: string) => {
      setError(error);
      setIsFormValid(false);
    };

    const onSubmit = () => {
      if (email != "") {
        if (isEmail(email)) {
          if (password != "") {
            if (confirmPassword != "") {
              if (confirmPassword == password) {
                validateForm();
              } else {
                invalidateForm(NOT_MATCHING_PASSWORD);
              }
            } else {
              invalidateForm(EMPTY_FIELD);
            }
          } else {
            invalidateForm(EMPTY_FIELD);
          }
        } else {
          invalidateForm(INVALID_EMAIL);
        }
      } else {
        invalidateForm(EMPTY_FIELD);
      }
    };

    return (
      <View className="gap-4" {...ref} {...props}>
        <View className="gap-4">
          <TextInput
            beforeIcon="mail"
            placeholder="Test@Optifit.com"
            onChangeText={setEmail}
            value={email}
            label={"Adresse mail"}
          />
          <PasswordTextInput
            onChangeText={setPassword}
            value={password}
            label={"Mot de passe"}
          />
          <PasswordTextInput
            onChangeText={setConfirmPassword}
            value={confirmPassword}
            label={"Confirmation du mot de passe"}
          />
        </View>
        <FormError isVisible={!isFormValid}>{error}</FormError>
        <Button onPress={onSubmit} afterIcon="arrowright">
          S'inscrire
        </Button>
      </View>
    );
  }
);
