import React from "react";
import { __, sprintf } from "@wordpress/i18n";
import { Link } from "react-router-dom";
import { Blocks } from "lucide-react";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import ProOnlyMessage from "@/components/ProOnlyMessage";
import { getModule, isModuleAvailable, isModuleEnabled } from "@libs/modules";

/**
 * Render a module's admin page only while its module is switched on.
 *
 * A switched-off module shows a notice linking to the Modules screen, and a
 * module whose code is missing (for Pro modules: Pro inactive or unlicensed)
 * shows the Pro message. Neither renders the page, so it never calls REST
 * routes that are not registered.
 *
 * @param {Object}          props
 * @param {string}          props.module   Module ID.
 * @param {string}          props.title    Page title for the notice screen.
 * @param {React.ReactNode} props.children The module page.
 */
const ModuleGate = ({ module: moduleId, title, children }) => {
  if (!isModuleAvailable(moduleId)) {
    return (
      <DefaultPageLayout title={title}>
        <ProOnlyMessage />
      </DefaultPageLayout>
    );
  }

  if (isModuleEnabled(moduleId)) {
    return children;
  }

  const moduleTitle = getModule(moduleId)?.title || title;

  return (
    <DefaultPageLayout title={title}>
      <div className="arraysubs-pro-only-message arraysubs-module-disabled-message">
        <div className="arraysubs-pro-only-message__icon">
          <Blocks size={44} aria-hidden="true" />
        </div>
        <h2 className="arraysubs-pro-only-message__title">
          {sprintf(
            /* translators: %s: module title. */
            __("%s is switched off", "arraysubs"),
            moduleTitle,
          )}
        </h2>
        <p className="arraysubs-pro-only-message__description">
          {__(
            "This module is switched off on the Modules screen. Switch it on to use this page.",
            "arraysubs",
          )}
        </p>
        <Link
          to="/modules"
          className="button button-primary arraysubs-module-disabled-message__action"
        >
          {__("Go to Modules", "arraysubs")}
        </Link>
      </div>
    </DefaultPageLayout>
  );
};

export default ModuleGate;
