import { createContext } from "preact";
import Login from "./Login";
import PocketBase from 'pocketbase';
import { useContext, useEffect, useState } from "preact/hooks";
import Home from "./Members/Home";

const pb = new PocketBase(import.meta.env.PUBLIC_PB_API);
export const Pb = createContext(pb);

export const Router = createContext({
  navigate: (path: string) => {
    console.log(path);
  },
});

export function useAuth() {
  const pb = useContext(Pb);
  const router = useContext(Router);
  const [isAuth, setIsAuth] = useState(pb.authStore.isValid);

  const login = async (email: string, password: string) => {
    try {
      await pb.collection('users').authWithPassword(email, password);
      router.navigate('/');
      setIsAuth(true)
    } catch (error) {
      return error;
    }
  }

  const logout = () => {
    try {
      pb.authStore.clear()
      setIsAuth(false)
    } catch (error) {
      return error;
    }
  }

  return {
    isAuth,
    login,
    logout,
  }
}

export default function EspaceMembres() {
  const [route, setRoute] = useState('/');
  const { isAuth } = useAuth();
  
  useEffect(() => {
    if (!isAuth) {
      setRoute('/login');
    }
  }, [isAuth]);

  const navigate = (path: string) => {
    setRoute(path);
  }

  return (
    <Pb.Provider value={pb}>
      <Router.Provider value={{
        navigate,
      }}>
        {{
          '/': <Home />,
          '/login': <Login />,
        }[route]}
      </Router.Provider>
    </Pb.Provider>
  )
}
