import React, { useState } from "react";
import * as api from "./../api/api";

const AuthContext = React.createContext({
  accessToken: "",
  refreshToken: "",
  isLoggedIn: false,
  login: (accessToken, refreshToken) => {},
  logout: () => {},
  role: null,
});

export const AuthContextProvider = (props) => {
  let initalAccessToken = localStorage.getItem("accessToken");
  let initialRefreshToken = localStorage.getItem("refreshToken");
  let initalRole = localStorage.getItem("role");

  const [accessToken, setAccessToken] = useState(initalAccessToken);
  const [refreshToken, setRefreshToken] = useState(initialRefreshToken);
  const [role, setrole] = useState(initalRole);
  const userIsLoggedIn = !!accessToken;

  const loginHandler = (accessToken, refreshToken, roleParam) => {
    setAccessToken(accessToken);
    setRefreshToken(refreshToken);
    localStorage.setItem("accessToken", accessToken);
    localStorage.setItem("refreshToken", refreshToken);
    setrole(roleParam);
    localStorage.setItem("role", roleParam);
  };

  const refreshTheToken = () => {
    api.refreshToken(refreshToken).then((data) => {
      setAccessToken(data.accessToken);
      localStorage.setItem("accessToken", data.accessToken);
    });
  };

  const logoutHandler = () => {
    setAccessToken(null);
    setRefreshToken(null);
    localStorage.removeItem("accessToken");
    localStorage.removeItem("refreshToken");
    setrole(null);
    localStorage.removeItem("role");
  };

  const contextvalue = {
    accessToken: accessToken,
    refreshToken: refreshToken,
    isLoggedIn: userIsLoggedIn,
    login: loginHandler,
    logout: logoutHandler,
    refresh: refreshTheToken,
    role: role,
  };

  return (
    <AuthContext.Provider value={contextvalue}>
      {props.children}
    </AuthContext.Provider>
  );
};

export default AuthContext;
