import { useEffect } from "react";
import { Navigate, useParams } from "react-router-dom";

import type { ModuleKey } from "@platform-types";
import { getModuleDefinition } from "@platform-config";

import { getModuleLaunchUrl } from "../config/runtime";
import { canAccessTenantModule, describeTenantAccess, getTenantDefaultPath } from "../config/workspace";
import { usePortalSession } from "../context/PortalSessionContext";

export function ModuleLaunchPage() {
  const { moduleKey } = useParams();
  const { currentUser } = usePortalSession();
  const module = moduleKey ? getModuleDefinition(moduleKey as ModuleKey) : undefined;

  if (!module) {
    return <Navigate to={getTenantDefaultPath(currentUser?.role, currentUser?.permissions)} replace />;
  }

  if (!canAccessTenantModule(currentUser?.role, currentUser?.permissions, module.key)) {
    return (
      <section className="panel narrow-panel stack-md">
        <p className="eyebrow">Accesso non autorizzato</p>
        <h2 className="page-title">Questo modulo non e disponibile per il tuo account</h2>
        <p className="muted-copy">
          Non hai accesso a {describeTenantAccess("/modules/placeholder", module.key)}. Se ti serve, chiedi
          l&apos;abilitazione all&apos;amministratore del locale.
        </p>
      </section>
    );
  }

  if (module.key === "homemade") {
    return <Navigate to="/homemade" replace />;
  }

  const launchUrl = getModuleLaunchUrl(module.key);
  if (!launchUrl) {
    return <Navigate to={getTenantDefaultPath(currentUser?.role, currentUser?.permissions)} replace />;
  }

  useEffect(() => {
    window.location.replace(launchUrl);
  }, [launchUrl]);

  return (
    <section className="panel narrow-panel stack-md">
      <p className="eyebrow">Apertura modulo</p>
      <h2 className="page-title">Sto aprendo {module.name}</h2>
      <p className="muted-copy">Verrai reindirizzato automaticamente.</p>
    </section>
  );
}
