import React, { createContext, useContext, useEffect, useMemo, useState } from "react";
import { useUserType, useJWTAuthentication } from "../../hooks";
import { Nullable, TUserData } from "../../types";
import { fetchUserData } from "../../api";

type AuthProviderProps = {
  children: JSX.Element;
};

export enum UserType {
  Individual = `individual`,
  JuridicalPerson = `entity`,
}

type ContextType = {
  isAuthorized: boolean;
  isJuridicalUser: boolean;
  changeUserType: (value: UserType) => void;
  personalInfo: Nullable<TUserData>;
};

const AuthStatusContext = createContext<ContextType>({
  isAuthorized: false,
  isJuridicalUser: false,
  changeUserType: null,
  personalInfo: null,
});

/**
 * Context that enables any component to get the current auth state
 * user type and rerender if it changes
 * @param props
 * @param props.children
 */
export const UserProvider = ({ children }: AuthProviderProps): JSX.Element => {
  const [personalInfo, setPersonalInfo] = useState<Nullable<TUserData>>(null);
  const { isJuridicalUser, changeUserType } = useUserType();
  const isAuthorized = useJWTAuthentication();
  const userData = useMemo(
    () => ({ isAuthorized, isJuridicalUser, changeUserType, personalInfo }),
    [isJuridicalUser, isAuthorized, changeUserType, personalInfo],
  );
  // Fetching user data
  useEffect(() => {
    (async () => {
      if (isAuthorized) {
        try {
          const personalInfo = await fetchUserData();

          if (personalInfo) setPersonalInfo(personalInfo);
        } catch (err) {
          console.warn(`Ошибка загрузки персональных данных. ${err}`);
        }
      }
    })();
  }, [isAuthorized]);

  return <AuthStatusContext.Provider value={userData}>{children}</AuthStatusContext.Provider>;
};

export const useUser = (): ContextType => useContext(AuthStatusContext);
