import { Platform, View } from "react-native";
import React, { useEffect, useState } from "react";
import Page from "../../layouts/Page";
import { background } from "../../assets";
import { gutters, Palette } from "../../styles";
import { responsiveHeight } from "react-native-responsive-dimensions";
import { BlurView } from "expo-blur";
import EditInput from "./components/EditInput";
import GradientButton from "../../components/GradientButton";
import { useGlobal } from "reactn";
import firebase, { usersRef } from "../../config/firebase";
import { goBack } from "../../navigation/NavigationService";
import { checkIfEmailIsValid } from "../../actions/signupActions";
import { Text } from "react-native";
import { FONT_FAMILY } from "../../styles/Fonts";

const ChangeEmailAddress = () => {
  const [email, setEmail] = useState("");
  const [originalEmail, setOriginalEmail] = useState("");
  const [emailError, setEmailError] = useState("");
  const [, setTooltip] = useGlobal("_tooltip");
  const [currentUserData] = useGlobal("currentUserData");
  const [loading, setLoading] = useState(false);
  const [currentPassword, setCurrentPassword] = useState("");

  useEffect(() => {
    const authEmail = firebase.auth().currentUser?.email || "";
    const profileEmail = (currentUserData?.email || authEmail || "").trim();
    setEmail((prev) => (prev ? prev : profileEmail));
    setOriginalEmail(profileEmail);
  }, [currentUserData?.email]);

  const onChangeEmail = (val) => {
    setEmail(val);
    const trimmed = (val || "").trim();
    if (trimmed.length === 0) {
      setEmailError("");
      return;
    }
    if (!checkIfEmailIsValid({ email: trimmed })) {
      setEmailError("Adresse email invalide");
    } else {
      setEmailError("");
    }
  };

  const onSave = async () => {
    const val = (email || "").trim();
    if (!val) return;
    try {
      setLoading(true);
      const user = firebase.auth().currentUser;
      const uid = user?.uid;
      if (!user || !uid) return;

      // Reauthenticate user with current password before sensitive update
      try {
        const credential = firebase.auth.EmailAuthProvider.credential(
          user.email,
          currentPassword,
        );
        await user.reauthenticateWithCredential(credential);
      } catch (reauthErr) {
        throw {
          code: "auth/wrong-password",
          message: "Mot de passe incorrect.",
        };
      }

      await user.updateEmail(val);
      await usersRef.doc(uid).set({ email: val }, { merge: true });
      setTooltip({ type: "success", text: "Email mis à jour" });
      goBack();
    } catch (e) {
      console.log("ChangeEmailAddress error", e?.message);
      const msg =
        e?.code === "auth/requires-recent-login"
          ? "Veuillez vous reconnecter pour changer l'adresse email"
          : e?.message || "Mise à jour impossible";
      setTooltip({ type: "error", text: msg });
    } finally {
      setLoading(false);
    }
  };
  return (
    <Page
      headerType="NAVIGATE"
      title="Paramètres"
      backgroundImg={background.profileBG}
      contentContainerStyle={{
        paddingBottom: gutters * 4,
      }}
      containerStyle={{
        backgroundColor: "#0000004D",
      }}
    >
      <View style={{ flex: 1, marginTop: responsiveHeight(2) }}>
        <BlurView
          intensity={20}
          style={{
            paddingHorizontal: 20,
            paddingVertical: 23,
            borderRadius: 20,
            overflow: "hidden",
            backgroundColor: Palette.glass,
          }}
          experimentalBlurMethod={
            Platform.OS !== "ios" ? "dimezisBlurView" : "none"
          }
        >
          <EditInput
            placeholder="Adresse mail"
            label="Adresse mail"
            value={email}
            setValue={onChangeEmail}
            type="email-address"
          />
          <View style={{ height: 10 }} />
          <EditInput
            placeholder="Mot de passe actuel"
            label="Mot de passe actuel"
            value={currentPassword}
            setValue={setCurrentPassword}
            type="password"
          />
          {!!emailError && (
            <Text
              style={{
                fontSize: 12,
                color: Palette.red,
                fontFamily: FONT_FAMILY.InterRegular,
                marginTop: 6,
              }}
            >
              {emailError}
            </Text>
          )}
        </BlurView>
      </View>
      <GradientButton
        title={loading ? "Chargement..." : "Enregistrer les modifications"}
        containerStyle={{
          width: "80%",
          alignSelf: "center",
        }}
        onPress={onSave}
        disabled={
          loading ||
          !email?.trim() ||
          !!emailError ||
          email.trim() === originalEmail.trim() ||
          !currentPassword?.trim()
        }
      />
    </Page>
  );
};

export default ChangeEmailAddress;
