"use client";
import type React from "react";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { usePathname } from "next/navigation";
import { setSidebarOpen } from "@/src/redux/appActions";
import { useScreenSizeContext } from "@/src/utils/providers/screenSizesContext";
import AdminSidebar from "@/src/components/admin/sidebar";
import AdminTopbar from "@/src/components/admin/topBar";
import AuthGuard from "@/src/components/reusables/auth";
import { useAppSelector } from "@/src/redux/hook";
import { RootState } from "@/src/redux/store";

export default function AdminLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const dispatch = useDispatch();
  const pathname = usePathname();
  const { isMobile, isTablet } = useScreenSizeContext();

  const isLoggedin = useAppSelector(
    (state: RootState) => state.auth.isLoggedIn
  );

  // Close sidebar on mobile when navigating
  useEffect(() => {
    if (isMobile || isTablet) {
      dispatch(setSidebarOpen(false));
    }
  }, [pathname, dispatch, isMobile, isTablet]);

  // Set sidebar open by default on desktop
  useEffect(() => {
    if (!isMobile && !isTablet) {
      dispatch(setSidebarOpen(true));
    }
  }, [isMobile, isTablet, dispatch]);

  if (
    pathname.startsWith("/admin/login") ||
    pathname.startsWith("/admin/forgot-password")
  ) {
    return <>{children}</>;
  }

  return (
    // <AuthGuard>
    <div className="flex h-screen overflow-hidden bg-[#F6F6F6]">
      {isLoggedin && <AdminSidebar />}
      <div className="flex flex-col flex-1 overflow-hidden">
        {isLoggedin && <AdminTopbar />}
        <main className="flex-1 overflow-y-auto p-4 md:p-6">{children}</main>
      </div>
    </div>
    // </AuthGuard>
  );
}
