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

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

type ContextProps = {
  children: ReactNode
}

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

export function ProvideAuth(props: Readonly<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 [trusted, setTrusted] = useState<boolean | undefined>();
  const [token, setToken] = useState<string | undefined>(getToken());
  const { decodedToken } = useJwt(token ?? '');

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

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

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

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