import { ReactNode, useEffect, useState } from 'react';
import { UserContext } from './UserContext.tsx';
import { refresh } from '@lib/account.ts';
import { User } from '@lib/account.types.ts';
import { Center, Loader } from '@mantine/core';

export function UserProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | undefined>(undefined);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    refresh().then((refreshUser) => {
      if (refreshUser) {
        setUser(refreshUser);
      } else {
        setUser(undefined);
      }
      setLoading(false);
    });
  }, []);

  return (
    <UserContext.Provider value={{ user, setUser, loading }}>
      {loading ? (
        <Center style={{ height: '100vh' }}>
          <Loader size='xl' />
        </Center>
      ) : (
        <>{children}</>
      )}
    </UserContext.Provider>
  );
}
