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

const AuthContext = createContext<{
  auth: { valid: boolean; user: User };
  setAuth: Dispatch<SetStateAction<{ valid: boolean; user: User }>>;
}>({ auth: {
  valid: false,
  user: {
    vatsimId: '',
    fullName: '',
    administrator: false,
    airportConfigurationAccess: [],
  },
}, setAuth: () => {} });

export const AuthProvider = ({ children }: { children: any }) => {
  const [auth, setAuth] = useState<{ valid: boolean; user: User }>({
    valid: false,
    user: {
      vatsimId: '',
      fullName: '',
      administrator: false,
      airportConfigurationAccess: [],
    },
  });
  const navigate = useNavigate();

  useEffect(() => {
    Auth.user().then((user) => {
      setAuth({ valid: true, user });
    }).catch(() => {
      setAuth({
        valid: false,
        user: {
          vatsimId: '',
          fullName: '',
          administrator: false,
          airportConfigurationAccess: [],
        },
      });
      navigate('/');
    });
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

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

export default AuthContext;
