import { useEffect, useRef } from "react";
import { createRoot, type Root } from "react-dom/client";
import {
  UserManagementApp,
  type UserManagementRuntimeOptions,
  type UserManagementSessionSeed,
} from "@tria-plc/iamui";

import { getCookie } from "@/auth/cookies";

import { iamConfig } from "./iamConfig";

function readInitialSession(): UserManagementSessionSeed | null {
  const token = getCookie("auth-token");

  if (!token) {
    return null;
  }

  const refreshToken = getCookie("refresh-token") ?? undefined;

  return {
    token,
    refreshToken,
    rememberMe: true,
  };
}

export default function UserManagementHostPage() {
  const mountRef = useRef<HTMLDivElement | null>(null);
  const rootRef = useRef<Root | null>(null);
  const unmountTimerRef = useRef<number | null>(null);

  useEffect(() => {
    const mountNode = mountRef.current;

    if (!mountNode) {
      return;
    }

    if (unmountTimerRef.current !== null) {
      window.clearTimeout(unmountTimerRef.current);
      unmountTimerRef.current = null;
    }

    if (!rootRef.current) {
      rootRef.current = createRoot(mountNode);
    }

    const apiBaseUrl = import.meta.env.VITE_BASE_API_URL.replace(/\/+$/, "");
    const iamApiUrl = "/um-api";
    const runtime: UserManagementRuntimeOptions = {
      basename: "/um",
      apiBaseUrl,
      apiUrl: iamApiUrl,
      recordApiUrl: iamApiUrl,
      chronicleUrl: iamApiUrl,
      auditApiUrl: iamApiUrl,
    };

    rootRef.current.render(
      <UserManagementApp
        config={iamConfig}
        runtime={runtime}
        session={{
          initialSession: readInitialSession(),
          enableEmbeddedAuthBridge: false,
        }}
      />,
    );

    return () => {
      unmountTimerRef.current = window.setTimeout(() => {
        rootRef.current?.unmount();
        rootRef.current = null;
        unmountTimerRef.current = null;
      }, 0);
    };
  }, []);

  return <div ref={mountRef} style={{ position: "fixed", inset: 0 }} />;
}
