"use client";
import React, { useEffect } from "react";
import { useAppSelector } from "@/src/redux/hook";
import { RootState } from "@/src/redux/store";
import { useRouter } from "next/navigation";
import { usePathname } from "next/navigation";
import SectionSkeleton from "../ui/Loading";

type Props = {
  children: React.ReactNode;
};

export default function AuthGuard({ children }: Props) {
  const isLoggedIn = useAppSelector(
    (state: RootState) => state.auth.isLoggedIn
  );

  const pathname = usePathname();
  const router = useRouter();

  useEffect(() => {
    if (isLoggedIn === undefined || isLoggedIn === null) return;

    console.log(pathname, "her");
    console.log(isLoggedIn, pathname, "Auth state");

    if (!isLoggedIn && (pathname?.includes("user") || pathname === "/")) {
      router.replace("/");
    } else if (!isLoggedIn && pathname?.includes("admin")) {
      router.replace("/admin/login");
    } else if (isLoggedIn && pathname?.includes("admin/login")) {
      router.replace("/admin/dashboard");
    }
  }, [isLoggedIn, pathname, router]);

  return <React.Fragment>{children}</React.Fragment>;
}
