import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { StyleSheet, View } from "react-native";
import { Text } from "react-native-paper";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectSignInError } from "../../redux/user/user.selectors";

const mapStateToProps = createStructuredSelector({
  signInError: selectSignInError,
});

function SignInError({ signInError }) {
  const [errorText, setErrorText] = useState("");
  const { t } = useTranslation();

  useEffect(() => {
    let text;
    if (signInError && signInError.code) {
      switch (signInError.code) {
        case "auth/user-not-found":
          text = t("signin.errors.wronginfo");
          break;
        case "auth/invalid-email":
          text = t("signin.errors.wronginfo");
          break;
        case "auth/wrong-password":
          text = t("signin.errors.wronginfo");
          break;
        default:
          text = signInError.code + " " + signInError.message;
          break;
      }
      setErrorText(text);
    }
  }, [t, signInError, setErrorText]);
  return (
    <View>
      {errorText ? <Text style={localStyles.alert}>{errorText}</Text> : null}
    </View>
  );
}

export default connect(mapStateToProps, null)(SignInError);

const localStyles = StyleSheet.create({
  alert: {
    color: "red",
    textAlign: "center",
    margin: 15,
    padding: 15,
  },
});
