import React, { useReducer } from "react";
import MkdSDK from "./utils/MkdSDK";

export const AuthContext = React.createContext({
  state: {
    isAuthenticated: false,
    user: null,
    userName: null,
    token: null,
    role: null,
    sessionExpired: null,
    photo: null,
    companyName: null,
    subscriptionStatus: null,
  },
  dispatch: () => null,
});

const initialState = {
  isAuthenticated: false,
  user: null,
  userName: null,
  token: null,
  role: null,
  sessionExpired: null,
  photo: null,
  companyName: null,
  subscriptionStatus: null,
};

const reducer = (state, action) => {
  switch (action.type) {
    case "LOGIN":
      localStorage.setItem("user", Number(action.payload.user_id));
      if (action.payload.first_name) {
        localStorage.setItem(
          "userName",
          action.payload.first_name + " " + action.payload.last_name
        );
      }

      localStorage.setItem("token", action.payload.token);
      localStorage.setItem("role", action.payload.role);
      localStorage.setItem("photo", action.payload?.photo);
      return {
        ...state,
        isAuthenticated: true,
        user: Number(localStorage.getItem("user")),
        userName: localStorage.getItem("userName"),
        token: localStorage.getItem("token"),
        role: localStorage.getItem("role"),
        photo: localStorage.getItem("photo"),
        companyName: localStorage.getItem("companyName"),
      };
    case "LOGOUT":
      localStorage.removeItem("user");
      localStorage.removeItem("userName");
      localStorage.removeItem("token");
      return {
        ...state,
        isAuthenticated: false,
        user: null,
      };
    case "SESSION_EXPIRED":
      return {
        ...state,
        sessionExpired: true,
      };
    case "SUBSCRIPTION_STATUS":
      return {
        ...state,
        subscriptionStatus: action.payload.subscriptionStatus,
      };
    case "SET_PROFILE":
      localStorage.setItem("photo", action.payload.photo);
      localStorage.setItem("companyName", action.payload.companyName);
      return {
        ...state,
        photo: action.payload.photo,
        companyName: action.payload.companyName,
      };
    default:
      return state;
  }
};

let sdk = new MkdSDK();

export const tokenExpireError = (dispatch, errorMessage) => {
  /**
   * either this or we pass the role as a parameter
   */
  const role = localStorage.getItem("role");
  if (errorMessage === "TOKEN_EXPIRED") {
    dispatch({ type: "SESSION_EXPIRED" });
    // dispatch({
    //   type: "LOGOUT",
    // });

    // location.href = "/" + role + "/login";
  }
};

const AuthProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState);

  React.useEffect(() => {
    const user = localStorage.getItem("user");
    const token = localStorage.getItem("token");
    const role = localStorage.getItem("role");

    if (token) {
      // let subscriptionResult;

      // // If no subscription, redirect to onboarding
      // if (
      //   !subscriptionResult?.customer?.planId &&
      //   role == "member" &&
      //   !localStorage.getItem("subscribed") &&
      //   window.location.pathname !== "/member/onboarding"
      // ) {
      //   dispatch({
      //     type: "SUBSCRIPTION_STATUS",
      //     payload: { subscriptionStatus: false },
      //   });
      //   localStorage.setItem("subscribed", true);
      //   window.location.href = "/member/onboarding";
      //   return;
      // }
      (async function () {
        try {
          const result = await sdk.check(role);
          dispatch({
            type: "LOGIN",
            payload: {
              user_id: user,
              token,
              role: role,
              photo: localStorage.getItem("photo"),
            },
          });
        } catch (error) {
          if (role) {
            localStorage.removeItem("workOrderSearchFilter");
            dispatch({
              type: "LOGOUT",
            });
            window.location.href = "/" + role + "/login";
          } else if (localStorage.getItem("subscribed")) {
            window.location.href = "/" + role + "/login";
          } else {
            localStorage.removeItem("workOrderSearchFilter");
            dispatch({
              type: "LOGOUT",
            });
            window.location.href = "/";
          }
        }
      })();
    }
  }, []);

  return (
    <AuthContext.Provider
      value={{
        state,
        dispatch,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export default AuthProvider;
