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

const userService = new UserServiceStub();

export default React.forwardRef<any, ViewProps>(
  ({ ...props }, ref): React.ReactElement => {
    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();
            const user = userService.login(email, password);
            if (user) {
              signIn(user);
              router.replace("/HomeScreen");
            } else {
              invalidateForm("Email ou mot de passe incorrect");
            }
          } 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
            label="Mot de passe"
            onChangeText={setPassword}
            value={password}
          />
        </View>
        <FormError isVisible={!isFormValid}>{error}</FormError>
        <Button onPress={onSubmit} afterIcon="arrowright">
          Se connecter
        </Button>
      </View>
    );
  }
);
