import { useContext, createContext, useGlobal } from "reactn";
import { useDataFromRef } from "react-native-minuit/src/hooks";
import useMinuit from "react-native-minuit/src/hooks/useMinuit";

import firebase, { usersRef } from "../config/firebase";
import { useState } from "react";
import { checkIfEmailIsValid } from "../actions/signupActions";

export const UserDataContext = createContext();

export default ({ children }) => {
  const { setIsLoading, setTooltip } = useMinuit();

  const [pendingUserData, setPendingUserData] = useState({
    creationTimestamp: new Date(),
  });

  const [currentUID] = useGlobal("currentUID");
  const [currentUserData, setCurrentUserData] = useGlobal("currentUserData");
  const [currentUserRoles] = useGlobal("currentUserRoles");

  useDataFromRef({
    ref: currentUID ? usersRef.doc(currentUID) : null,
    simpleRef: true,
    listener: true,
    condition: currentUID,
    refreshArray: [currentUID],
    onUpdate: (data) => {
      if (data) {
        setCurrentUserData(data);
      } else {
        setCurrentUserData(null);
      }
    },
  });

  const updatePendingUserData = (newData) => {
    setPendingUserData((prevData) => ({
      ...prevData,
      ...newData,
    }));
  };

  const updateUserData = async ({ data, shouldSetTooltip = true }) => {
    try {
      await setIsLoading(true);

      let dynamicUID = currentUID || null;

      let cleanData = {
        ...currentUserData,
        ...data,
        lastUpdateTimestamp: new Date(),
      };

      // if (cleanData?.firstName?.length > 2 && cleanData?.lastName?.length > 2) {
      //   cleanData = {
      //     ...cleanData,
      //     firstName: capitalize(cleanData?.firstName?.toLowerCase()),
      //     lastName: capitalize(cleanData?.lastName?.toLowerCase()),
      //   };
      // } else {
      //   throw new Error("Veuillez renseigner un prénom et un nom");
      // }

      if (!checkIfEmailIsValid({ email: cleanData?.email })) {
        throw new Error("Veuillez renseigner un email valide");
      }

      // let cleanPhoneNumber = formatPhoneNumber({
      //   phoneNumber: cleanData.phoneNumber,
      // });

      // if (cleanPhoneNumber) {
      //   cleanData.phoneNumber = cleanPhoneNumber;
      // } else {
      //   throw new Error("Veuillez renseigner un numéro de téléphone valide");
      // }

      if (!dynamicUID) {
        const { email, password } = cleanData;

        const { user = null } = await firebase
          .auth()
          .createUserWithEmailAndPassword(email, password);

        dynamicUID = user.uid;
      }

      delete cleanData.password;

      cleanData = {
        ...cleanData,
        userID: dynamicUID,
      };

      if (!cleanData?.creationTimestamp) {
        cleanData.creationTimestamp = new Date();
      }

      console.log("cleanData", cleanData);

      await usersRef.doc(dynamicUID).set(cleanData, { merge: true });

      if (shouldSetTooltip) {
        setTooltip({
          type: "success",
          text: "Données enregistrées avec succès",
        });
      }
    } catch (e) {
      console.log(e);

      setTooltip({
        type: "error",
        text: "Erreur lors de la mise à jour des données utilisateur",
      });

      throw e;
    } finally {
      await setIsLoading(false);
    }
  };

  const onSignOut = async () => {
    try {
      setIsLoading(true);

      await firebase.auth().signOut();
    } catch (e) {
      console.log(e);
    } finally {
      setIsLoading(false);
    }
  };

  const isSuperAdmin = currentUserRoles.some((role) => role === "SUPERADMIN");

  return (
    <UserDataContext.Provider
      value={{
        isSuperAdmin,

        currentUserRoles,
        currentUID,
        currentUserData,

        setCurrentUserData,

        onSignOut,

        pendingUserData,
        updatePendingUserData,

        updateUserData,
      }}
    >
      {children}
    </UserDataContext.Provider>
  );
};

export const useUserData = () => {
  return useContext(UserDataContext);
};
