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

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

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

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

    const onSubmit = () => {
      if (email != "") {
        if (isEmail(email)) {
          if (password != "") {
            validateForm();
            signIn();
            router.replace("/HomeScreen");
          } else {
            invalidateForm(EMPTY_FIELD);
          }
        } else {
          invalidateForm(INVALID_EMAIL);
        }
      } else {
        invalidateForm(EMPTY_FIELD);
      }
    };

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