import React, { useEffect } from "react";
import {
  ScrollView,
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Alert,
} from "react-native";

import InputField from "@components/InputField";

import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import Ionicons from "@expo/vector-icons/Ionicons";

import RegistrationSVG from "@assets/images/registration.svg";
import GoogleSVG from "@assets/images/google.svg";
import FacebookSVG from "@assets/images/facebook.svg";
import TwitterSVG from "@assets/images/twitter.svg";

import CustomButton from "@components/Buttons/CustomButton";
import { globalStyles } from "@styles/global";
import Loader from "@components/Loader";
import { Formik } from "formik";
import { registerSchema } from "@schemas/registerSchema";
import { useDispatch, useSelector } from "react-redux";
import { selectRegisterError } from "@store/selectors/registerSelectors";
import { selectIsLoadingByActionType } from "@store/selectors/loadingSelectors";
import { REGISTER_USER_SCOPE } from "@store/actions/register/registerActionConstants";
import {
  clearRegisterErrors,
  registerUser,
} from "@store/actions/register/registerActions";
import useAuthHook from "../hooks/useAuthHook";
import { fetchAuthProvider } from "@store/actions/authProvider/authProviderActions";
import { ACCESS_TOKEN } from "@constants/localStorage";
import { storeData } from "@service/asyncStorage";
import Layout from "@components/Layout/Layout";
import { useTheme } from "@styles";
import { useTranslation } from "react-i18next";

const RegisterScreen = ({ navigation }) => {
  const { colors } = useTheme();
  const { t } = useTranslation();
  const { response, promptAsync } = useAuthHook();
  const dispatch = useDispatch();
  const error = useSelector(selectRegisterError);

  const isLoading = useSelector(
    selectIsLoadingByActionType(REGISTER_USER_SCOPE)
  );

  const storeToken = async (token) => {
    await storeData(ACCESS_TOKEN, token);
  };

  const handleApiResponseSuccess = () => {
    Alert.alert(t("common.success"), t("register.successRegisterAccount"), [
      {
        text: "OK",
        onPress: () => navigation.navigate("Login"),
      },
    ]);
  };

  const handleSignup = (values) => {
    const { username, email, password } = values;
    dispatch(clearRegisterErrors());
    dispatch(
      registerUser({ username, email, password, handleApiResponseSuccess })
    );
  };

  const handleGoogleAuth = () => {
    promptAsync({ useProxy: true, showInRecents: true });
  };

  useEffect(() => {
    if (response?.type === "success") {
      const accessToken = response.authentication.accessToken;
      if (accessToken) {
        storeToken(accessToken);
        dispatch(fetchAuthProvider({ accessToken }));
      }
    }
  }, [response]);

  return (
    <Layout>
      <Loader visible={isLoading} />
      <ScrollView
        showsVerticalScrollIndicator={false}
        style={{ paddingHorizontal: 25 }}
      >
        <View style={{ alignItems: "center" }}>
          <RegistrationSVG width={300} height={300} />
        </View>
        <Text style={[globalStyles.boldText, { color: colors.textPrimary }]}>
          {t("register.register")}
        </Text>
        <View style={styles.providersContainer}>
          <TouchableOpacity
            onPress={handleGoogleAuth}
            style={globalStyles.iconButton}
          >
            <GoogleSVG height={24} width={24} />
          </TouchableOpacity>
          <TouchableOpacity onPress={() => {}} style={globalStyles.iconButton}>
            <FacebookSVG height={24} width={24} />
          </TouchableOpacity>
          <TouchableOpacity onPress={() => {}} style={globalStyles.iconButton}>
            <TwitterSVG height={24} width={24} />
          </TouchableOpacity>
        </View>
        <Text
          style={[
            globalStyles.regularCenteredText,
            { color: colors.textPrimary },
          ]}
        >
          {t("register.orSignUpWithMail")}
        </Text>
        <Formik
          initialValues={{
            username: "",
            email: "",
            password: "",
            confirmPassword: "",
          }}
          validationSchema={registerSchema}
          onSubmit={handleSignup}
          validateOnChange={false}
          validateOnBlur={false}
        >
          {({
            handleChange,
            handleBlur,
            handleSubmit,
            values,
            isValid,
            errors,
          }) => (
            <>
              <InputField
                name={"username"}
                text={values.username}
                onChangeText={handleChange("username")}
                label={t("register.username")}
                handleBlur={handleBlur("username")}
                icon={
                  <Ionicons
                    name="person-outline"
                    size={20}
                    color="#666"
                    style={{ marginRight: 5 }}
                  />
                }
              />
              {errors.username && (
                <Text style={styles.errorMessage}>{errors.username}</Text>
              )}
              <InputField
                name={"email"}
                text={values.email}
                onChangeText={handleChange("email")}
                label={t("register.email")}
                handleBlur={handleBlur("email")}
                icon={
                  <MaterialIcons
                    name="alternate-email"
                    size={20}
                    color="#666"
                    style={{ marginRight: 5 }}
                  />
                }
                keyboardType="email-address"
              />
              {errors.email && (
                <Text style={styles.errorMessage}>{errors.email}</Text>
              )}
              <InputField
                name={"password"}
                text={values.password}
                onChangeText={handleChange("password")}
                label={t("register.password")}
                handleBlur={handleBlur("password")}
                icon={
                  <Ionicons
                    name="ios-lock-closed-outline"
                    size={20}
                    color="#666"
                    style={{ marginRight: 5 }}
                  />
                }
                inputType="password"
              />
              {errors.password && (
                <Text style={styles.errorMessage}>{errors.password}</Text>
              )}
              <InputField
                name={"confirmPassword"}
                text={values.confirmPassword}
                onChangeText={handleChange("confirmPassword")}
                label={t("register.confirmPassword")}
                handleBlur={handleBlur("confirmPassword")}
                icon={
                  <Ionicons
                    name="ios-lock-closed-outline"
                    size={20}
                    color="#666"
                    style={{ marginRight: 5 }}
                  />
                }
                inputType="password"
              />
              {errors.confirmPassword && (
                <Text style={styles.errorMessage}>
                  {errors.confirmPassword}
                </Text>
              )}
              {error && <Text style={styles.errorMessage}>{error}</Text>}
              <CustomButton
                label={t("register.signUp")}
                onPress={handleSubmit}
              />
            </>
          )}
        </Formik>
        <View style={styles.alreadyRegistered}>
          <Text
            style={[globalStyles.regularText, { color: colors.textPrimary }]}
          >
            {t("register.alreadyRegistered")}{" "}
          </Text>
          <TouchableOpacity onPress={() => navigation.goBack()}>
            <Text style={globalStyles.primaryBold}>{t("register.signIn")}</Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </Layout>
  );
};

const styles = StyleSheet.create({
  providersContainer: {
    flexDirection: "row",
    justifyContent: "space-between",
    marginBottom: 30,
  },
  dateOfBirthContainer: {
    flexDirection: "row",
    borderBottomColor: "#ccc",
    borderBottomWidth: 1,
    paddingBottom: 8,
    marginBottom: 30,
  },
  dateOfBirthLabel: {
    color: "#666",
    marginLeft: 5,
    marginTop: 5,
  },
  alreadyRegistered: {
    flexDirection: "row",
    justifyContent: "center",
    marginBottom: 30,
  },
  errorMessage: {
    marginBottom: 30,
    color: "red",
  },
});

export default RegisterScreen;
