import React, { useState, useEffect, useContext } from 'react';
import { Result } from 'antd';
import { Loading3QuartersOutlined } from '@ant-design/icons';
import type { UserResult } from './users';
import { useGetCurrentUser } from './users';

const AuthContext = React.createContext<{
  user?: UserResult;
  refresh: () => void;
}>({ refresh: () => console.log('Missing AuthContext.Provider') });

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const [initialized, setInitialized] = useState(false);

  const { data: user, loading, refresh } = useGetCurrentUser();

  useEffect(() => {
    if (!loading) {
      setInitialized(true);
    }
  }, [loading]);

  return (
    <AuthContext.Provider value={{ user, refresh }}>
      {initialized ? (
        children
      ) : (
        <Result
          icon={<Loading3QuartersOutlined spin />}
          subTitle="Loading..."
        />
      )}
    </AuthContext.Provider>
  );
};

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