import { createContext, Dispatch, SetStateAction, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Auth } from '../services';
import { IAuthState } from '../types';

const InitialAuthState: IAuthState = {
  valid: false,
  user: {
    vatsimId: '',
    fullName: '',
    radarScopeKey: '',
    administrator: false,
    airportConfigurationAccess: [],
  },
};

const AuthContext = createContext<{
  auth: IAuthState;
  setAuth: Dispatch<SetStateAction<IAuthState>>;
  resetAuth: () => void;
}>({ auth: InitialAuthState, setAuth: () => {}, resetAuth: () => {} });

export const AuthProvider = ({ children }: { children: any }) => {
  const [auth, setAuth] = useState<IAuthState>(InitialAuthState);
  const navigate = useNavigate();

  const resetAuth = () => setAuth(InitialAuthState);

  useEffect(() => {
    Auth.user().then((user) => {
      if (user !== undefined) {
        setAuth({ valid: true, user });
      } else {
        setAuth(InitialAuthState);
      }
    }).catch(() => {
      setAuth(InitialAuthState);
      navigate('/');
    });
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <>
      <AuthContext.Provider value={{ auth, setAuth, resetAuth }}>
        {children}
      </AuthContext.Provider>
    </>
  );
};

export default AuthContext;
