import { User } from "@/interfaces/user";
import { sessionOptions } from "@/lib/session";
import { shouldRedirectHome } from "@/utils/navigation.disabled";
import { checkAccess } from "@/utils/permissions";
import { getUserPermissions } from "@/utils/permissions.be";
import { withIronSessionSsr } from "iron-session/next";
import dynamic from "next/dynamic";
import { useState, useEffect } from 'react';

export const getServerSideProps = withIronSessionSsr(async ({ req, res, query }) => {
  const user = req.session.user;
  if (!user) {
    return {
      redirect: {
        destination: "/login",
        permanent: false,
      },
    };
  }
  if (shouldRedirectHome(user) || !checkAccess(user, ["admin", "developer", "corporate", "teacher", "mastercorporate"])) {
    return {
      redirect: {
        destination: "/",
        permanent: false,
      },
    };
  }
  const permissions = await getUserPermissions(user.id);
  const {type, module} = query;
  return {
    props: { user, permissions, type, module },
  };
}, sessionOptions);

const Popout: React.FC<{ user: User; type: string, module: string }> = ({ user, type, module }) => {
  const [DynamicPopout, setDynamicPopout] = useState<React.ComponentType<any> | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadComponent = async () => {
      try { 
        const sanitizedPopout = type.replace(/[^a-zA-Z0-9]/g, '');
        const sanitizedModule = module.replace(/[^a-zA-Z0-9]/g, '');
        const Component = dynamic(() => import(`@/components/Popouts/${sanitizedPopout}`), {
          loading: () => (
            <div className="min-h-screen w-full">
              <div className="absolute left-1/2 top-1/2 flex h-fit w-fit -translate-x-1/2 -translate-y-1/2 animate-pulse flex-col items-center gap-12">
                <span className={`loading loading-infinity w-32 bg-ielts-${sanitizedModule}`} />
              </div>
            </div>
          ),
        });
        setDynamicPopout(() => Component);
      } catch (err) {
        console.error("Error loading component:", err);
        setError("Failed to load the requested popout component.");
      }
    };

    loadComponent();
  }, [type, module]);

  if (error) {
    return <div className="text-red-500">{error}</div>;
  }
  return (
    <div className="min-h-screen w-full p-10">
       {DynamicPopout ? <DynamicPopout user={user} /> : null}
    </div>
  );
};

export default Popout;
