import { Navigate, Outlet, createFileRoute } from "@tanstack/react-router";
import AppHeader from "../components/AppHeader";
import AppNavbar from "../components/AppNavbar";
import useAuth from "@/hooks/useAuth";
import { useQuery } from "@tanstack/react-query";
import fetchRPC from "@/utils/fetchRPC";
import client from "@/honoClient";
import { useState } from "react";

export const Route = createFileRoute("/_assessmentLayout")({
  component: AssessmentLayout,

  // beforeLoad: ({ location }) => {
  // 	if (true) {
  // 		throw redirect({
  // 			to: "/login",
  // 		});
  // 	}
  // },
});

function AssessmentLayout() {
  const { isAuthenticated, saveAuthData } = useAuth();

  useQuery({
    queryKey: ["my-profile"],
    queryFn: async () => {
      const response = await fetchRPC(client.auth["my-profile"].$get());

      saveAuthData({
        id: response.id,
        name: response.name,
        permissions: response.permissions,
        role: response.roles[0],
      });

      return response;
    },
    enabled: isAuthenticated,
  });

  const [openNavbar, setNavbarOpen] = useState(true);
  const toggle = () => {
    setNavbarOpen(!openNavbar);
  };

  return isAuthenticated ? (
    <div className="flex flex-col w-full h-screen overflow-hidden">
      {/* Header */}
      <AppHeader toggle={toggle} openNavbar={openNavbar} />

      {/* Main Content Area */}
      <div className="flex h-full w-screen overflow-hidden">
        {/* Sidebar */}
        <AppNavbar />

        {/* Main Content */}
        <main className="relative w-full mt-16 bg-white overflow-auto">
          <Outlet />
        </main>
      </div>
    </div>
  ) : (
    <Navigate to="/login" />
  );
}
