import React, { ReactNode, useContext, useState } from "react"
import { useEffect } from "react"
import { useJwt } from "react-jwt";
import { deleteToken, getToken, storeToken } from "../Utils";

export type AuthContextProps = {
  login?: string,
  setToken: (name: string) => void,
  logout: () => void,
}

type ContextProps = {
  children: ReactNode
}

const authContext = React.createContext<AuthContextProps | null>(null);

export function ProvideAuth(props: ContextProps) {
  const auth = useProvideAuth();
  return <authContext.Provider value={auth}>{props.children}</authContext.Provider>
}

export const useAuth = () => {
  return useContext(authContext);
}

function useProvideAuth(): AuthContextProps {
  const [loginName, setLoginName] = useState<string | undefined>();
  const [token, setToken] = useState<string | null>(getToken());
  const { decodedToken } = useJwt(token || '');

  useEffect(() => {
    if (token && token.length > 0) {
      storeToken(token);
    } else {
      deleteToken();
    }
  }, [token]);

  useEffect(() => {
    if (decodedToken) {
      setLoginName((decodedToken as any).login);
    } else {
      setLoginName(undefined);
    }
  }, [decodedToken]);

  function logout() {
    const trusted = (decodedToken as any).trusted;
    const logoutUrl = (decodedToken as any).logoutUrl;
    setToken(null);
    setLoginName(undefined);
    if (trusted && logoutUrl?.length) {
      window.location.replace(logoutUrl);
    }
  }

  return {
    login: loginName,
    setToken,
    logout,
  }
}
