import Button from "@/components/ui/Button";
import Screen from "@/components/ui/Screen";
import Text from "@/components/ui/Text";
import TextInput from "@/components/form/FormInput";
import BackButton from "@/components/BackButton";
import { View } from "react-native";
import React from "react";
import CodeSent from "@/components/modals/CodeSent";
import FormError from "@/components/form/FormError";
import { EMPTY_FIELD, INVALID_EMAIL } from "@/components/Errors";
import { isEmail } from "validator";

export default function ResetPasswordWithEmail() {
  const [isModalVisible, setIsModalVisible] = React.useState(false);
  const [email, setEmail] = 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)) {
        validateForm();
        setIsModalVisible(true);
      } else {
        invalidateForm(INVALID_EMAIL);
      }
    } else {
      invalidateForm(EMPTY_FIELD);
    }
  };

  return (
    <Screen>
      <CodeSent
        email={email}
        onPress={() => setIsModalVisible(false)}
        visible={isModalVisible}
      />
      <BackButton icon="close" />
      <View className="gap-4">
        <Text size="3xl" weight="bold">
          Recevoir un code par email
        </Text>
        <TextInput
          beforeIcon="mail"
          placeholder="Test@Optifit.com"
          onChangeText={setEmail}
          value={email}
          label={"Adresse mail"}
        />
        <FormError isVisible={!isFormValid}>{error}</FormError>
        <Button onPress={onSubmit} afterIcon="arrowright">
          Recevoir le code
        </Button>
      </View>
    </Screen>
  );
}
