"use client";

import React, { useState } from "react";
import { useSession, signOut } from "next-auth/react";
import { Box } from "@mui/material";
import AdminLeftPanelMenu from "@/app/components/AdminLeftPanelMenu";
import AdminRightContent from "@/app/components/AdminRightContent";
import { Metadata } from "next";

const drawerWidth = 240;
export const metadata: Metadata = {
  title: "3D Learning Hub Admin",
  description: "A hub for exploring and learning with 3D models",
};
export default function AdminLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const { data: session, status } = useSession();
  const [mobileOpen, setMobileOpen] = useState(false);
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);

  const handleDrawerToggle = () => {
    setMobileOpen(!mobileOpen);
  };

  const handleMenuOpen = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleMenuClose = () => {
    setAnchorEl(null);
  };

  const handleLogout = async () => {
    handleMenuClose();
    await signOut({ redirect: false });
    window.location.href = "/admin/login";
  };

  // If not authenticated, just render children (the login page handles its own UI)
  if (status === "unauthenticated") {
    return <>{children}</>;
  }

  if (status === "loading") {
    return <>Loading...</>; // Wait for auth proxy resolution without flash
  }

  return (
    <Box sx={{ display: "flex", minHeight: "100vh", backgroundColor: "#f9f9fc" }}>
      <AdminLeftPanelMenu
        drawerWidth={drawerWidth}
        mobileOpen={mobileOpen}
        onClose={handleDrawerToggle}
        onLogout={handleLogout}
      />
      <AdminRightContent
        drawerWidth={drawerWidth}
        userName={session?.user?.name}
        anchorEl={anchorEl}
        onMenuOpen={handleMenuOpen}
        onMenuClose={handleMenuClose}
        onLogout={handleLogout}
      >
        {children}
      </AdminRightContent>
    </Box>
  );
}
