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

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

export function SignInErrorAlertComponent({ 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.usernotfound");
          break;
        case "auth/invalid-email":
          text = t("signin.errors.emailformat");
          break;
        case "auth/wrong-password":
          text = t("signin.errors.wrongpassword");
          break;
        default:
          text = signInError.code + " " + signInError.message;
          break;
      }

    setErrorText(text);
  }, [signInError, setErrorText]);
  return (
    <View>
      {errorText ? <Title style={localStyles.alert}>{errorText}</Title> : null}
    </View>
  );
}

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

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