import { createContext, useContext, useState } from "react";
import { FC } from "react";
import { Login } from "./login";

export interface AuthContext {
  accessToken: string | null;
  setAccessToken: (token: string) => void;
  setRefreshToken: (token: string) => void;
  refreshToken: string | undefined;
  login: (dto: any) => void;
  account?: any;
  setAccount: (dto: any) => void;
  logout: () => void;
}
const Context = createContext({} as AuthContext);

export const useAuth = () => useContext(Context);

export const AuthProvider: FC = ({ children }) => {
  const [accessToken, setAccessToken] = useState<string | null>(
    localStorage.getItem("accessToken")
  );
  const [refreshToken, setRefreshToken] = useState<string>();
  const [account, setAccount] = useState<any>();

  const login = (dto: any) => {
    setAccessToken(dto.accessToken);
    setRefreshToken(dto.refreshToken);
    setAccount(dto.account);
    localStorage.setItem("accessToken", dto.accessToken);
  };
  const logout = () => {
    setAccessToken(null);
    setRefreshToken(undefined);
    setAccount(undefined);
  };

  return (
    <Context.Provider
      value={{
        accessToken,
        setAccessToken,
        refreshToken,
        setRefreshToken,
        login,
        account,
        setAccount,
        logout,
      }}
    >
      {children}
      {accessToken ? null : <Login />}
    </Context.Provider>
  );
};
