import { createContext, use, useCallback, useState, type PropsWithChildren } from 'react';

export type User = {
  id: string;
  name: string;
};

export type AuthProviderProps = PropsWithChildren<object>;
export type AuthContextType = {
  setUser: (user: User) => void;
  logOut: () => void;
  user: User | null;
};

const AuthContext = createContext<AuthContextType | null>(null);

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [user, setUserState] = useState<User | null>(null);

  const setUser = useCallback((user: User) => {
    setUserState(user);
  }, []);

  const logout = useCallback(() => {
    setUserState(null);
  }, []);

  return (
    <AuthContext
      value={{
        user: user,
        logOut: logout,
        setUser: setUser,
      }}
    >
      {children}
    </AuthContext>
  );
};

export function useAuth() {
  const context = use(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within a AuthProvider');
  }
  return context;
}
