import {useCollection} from "@nandorojo/swr-firestore";
import {NextPage} from "next";
import {useRouter} from "next/router";
import * as React from "react";

import AuthContext from "@sentrei/common/context/AuthContext";
import Space from "@sentrei/common/models/Space";
import {analytics} from "@sentrei/common/utils/firebase";
import Loader from "@sentrei/ui/components/Loader";
import SpaceDashboard from "@sentrei/ui/components/SpaceDashboard";
import useSnackbar from "@sentrei/ui/hooks/useSnackbar";
import SentreiAppHeader from "@sentrei/web/components/SentreiAppHeader";

const Dashboard: NextPage = () => {
  const {user} = React.useContext(AuthContext);
  const router = useRouter();
  const {snackbar} = useSnackbar();

  const {data: spaces, error} = useCollection<Space.Get>(
    user?.uid ? `users/${user.uid}/spaces` : null,
  );

  React.useEffect(() => {
    analytics().setCurrentScreen("dashboard");
  }, []);

  if (user === undefined) {
    return <Loader />;
  }

  if (!user) {
    router.push("/");
  }

  if (error) {
    snackbar("error", error?.message);
  }

  return (
    <>
      <SentreiAppHeader />
      {user && <SpaceDashboard spaces={spaces} />}
    </>
  );
};

export default Dashboard;
