import { useEffect, useRef, useState } from "react";
import { useLocation } from "react-router";
import { HelpCircle, Info, BookOpen, GitBranch } from "lucide-react";
import packageInfo from "../../package.json";
import Button from "../components/Button";
import Dialog from "../components/Dialog";
import { useGuardedNavigate } from "../components/UnsavedChangesGuard";
import { usePlatformModules } from "../platform/ModuleContext";
import type { PlatformWebModule } from "../types";
import { helpContextForPathname, helpQueryForContext, type HelpContext } from "../utils/helpContext";
import { usePlatformLanguage } from "../i18n/LanguageContext";
import type { AuthInfo } from "../types";
import { hasAnyScope } from "../utils/permissions";

const EXTERNAL_DOCS_BASE_URL = "https://govoplan.add-ideas.de";

export default function HelpMenu({ auth }: { auth: AuthInfo | null }) {
  const [open, setOpen] = useState(false);
  const [aboutOpen, setAboutOpen] = useState(false);
  const [contextOpen, setContextOpen] = useState(false);
  const wrapRef = useRef<HTMLDivElement>(null);
  const location = useLocation();
  const navigate = useGuardedNavigate();
  const helpContext = helpContextForPathname(location.pathname, location.search);
  const modules = usePlatformModules();
  const { translateText } = usePlatformLanguage();
  const adminDocsAvailable = hasAnyScope(auth, ["docs:documentation:admin", "system:settings:read", "admin:settings:read"]);
  const configuredDocsAvailable = hasAnyScope(auth, ["docs:documentation:read"]) || adminDocsAvailable;
  const docsAvailable = configuredDocsAvailable &&
    modules.some((module) => module.id === "docs" && module.routes?.some((route) => route.path === "/docs"));

  useEffect(() => {
    function openContextHelp(event: KeyboardEvent) {
      if (event.key !== "F1") return;
      event.preventDefault();
      event.stopPropagation();
      event.stopImmediatePropagation();
      setOpen(false);
      setContextOpen(true);
    }
    function onPointerDown(event: MouseEvent) {
      if (wrapRef.current && !wrapRef.current.contains(event.target as Node)) {
        setOpen(false);
      }
    }
    window.addEventListener("keydown", openContextHelp, true);
    window.addEventListener("mousedown", onPointerDown);
    return () => {
      window.removeEventListener("keydown", openContextHelp, true);
      window.removeEventListener("mousedown", onPointerDown);
    };
  }, []);

  function openHelp() {
    setOpen(false);
    setContextOpen(true);
  }

  function openDocs(type: "user" | "admin") {
    setOpen(false);
    setContextOpen(false);
    if (!docsAvailable) {
      window.open(externalDocsUrl(type, helpContext), "_blank", "noopener,noreferrer");
      return;
    }
    const params = new URLSearchParams({ type });
    params.set("context", helpContext.id);
    navigate(`/docs?${params.toString()}`);
  }

  return (
    <div className="context-menu-wrap" ref={wrapRef}>
      <button
        className="titlebar-link"
        onClick={() => setOpen(!open)}
        onKeyDown={(event) => {
          if (event.key === "F1") {
            event.preventDefault();
            event.stopPropagation();
            openHelp();
          }
        }}
        title={translateText("i18n:govoplan-core.help_f1")}>
        
        <HelpCircle size={17} /> {translateText("i18n:govoplan-core.help.c47ae153")}
      </button>
      {open &&
      <div className="dropdown-menu">
          <button className="dropdown-item" onClick={openHelp}>
            <HelpCircle size={16} /> {translateText("i18n:govoplan-core.help.c47ae153")} <small>i18n:govoplan-core.f1.88bfad9c</small>
          </button>
          <hr />
          <button className="dropdown-item" onClick={() => openDocs("user")} title={docsAvailable ? translateText("i18n:govoplan-core.open_user_documentation.084af515") : "Open hosted user documentation"}>
            <BookOpen size={16} /> {translateText("i18n:govoplan-core.user_docs.1e38e8d3")}
          </button>
          {adminDocsAvailable &&
            <button className="dropdown-item" onClick={() => openDocs("admin")} title={docsAvailable ? translateText("i18n:govoplan-core.open_admin_documentation.6adbdae3") : "Open hosted admin documentation"}>
              <BookOpen size={16} /> {translateText("i18n:govoplan-core.admin_docs.bf504a56")}
            </button>
          }
          <hr />
          <a className="dropdown-item" href="https://git.add-ideas.de/add-ideas" target="_blank" rel="noreferrer"><GitBranch size={16} /> i18n:govoplan-core.gitlab.9a9b09d9</a>
          <button className="dropdown-item" onClick={() => {setAboutOpen(true);setOpen(false);}}><Info size={16} /> {translateText("i18n:govoplan-core.about.6b21fb79")}</button>
        </div>
      }
      {contextOpen && <ContextHelpModal context={helpContext} onOpenDocs={() => openDocs("user")} onClose={() => setContextOpen(false)} />}
      {aboutOpen && <AboutModal modules={modules} onClose={() => setAboutOpen(false)} />}
    </div>);

}

function externalDocsUrl(type: "user" | "admin", context: HelpContext): string {
  const params = new URLSearchParams({ type, context: context.id });
  return `${EXTERNAL_DOCS_BASE_URL}/?${params.toString()}`;
}

function ContextHelpModal({ context, onOpenDocs, onClose }: {context: HelpContext;onOpenDocs: () => void;onClose: () => void;}) {
  const { translateText } = usePlatformLanguage();
  return (
    <Dialog
      open
      title={translateText("i18n:govoplan-core.context_help.7fc44ea1")}
      onClose={onClose}
      footer={<Button variant="primary" onClick={onClose}>{translateText("i18n:govoplan-core.close.bbfa773e")}</Button>}>
      
      <div className="help-panel-section" data-help-context={context.id}>
        <h3>{translateText(context.title)}</h3>
        <p className="mono-small">{translateText("i18n:govoplan-core.help_context.61aed3b9")} {context.id}</p>
        <p className="muted">{translateText("i18n:govoplan-core.this_area_is_prepared_for_context_sensitive_help.57665877")} <span className="kbd">{helpQueryForContext(context)}</span> {translateText("i18n:govoplan-core.to_open_the_right_page_or_section.5ecf4fd2")}</p>
      </div>
      <div className="help-panel-section">
        <h3>{translateText("i18n:govoplan-core.next_actions.7b09055a")}</h3>
        <p className="muted">{translateText("i18n:govoplan-core.the_first_guided_help_content_can_cover_campaign.14a6bd8a")}</p>
        <Button onClick={onOpenDocs}><BookOpen size={16} /> {translateText("i18n:govoplan-core.open_user_documentation.084af515")}</Button>
      </div>
    </Dialog>);

}

function AboutModal({ modules, onClose }: {modules: PlatformWebModule[];onClose: () => void;}) {
  const { translateText } = usePlatformLanguage();
  const moduleSummary = modules.length ?
  modules.map((module) => `${module.label} v${module.version}`).join(", ") :
  translateText("i18n:govoplan-core.core_shell_only.4949b5d5");

  return (
    <Dialog
      open
      title={translateText("i18n:govoplan-core.about_govoplan.1c6884f8")}
      onClose={onClose}
      footer={<Button variant="primary" onClick={onClose}>{translateText("i18n:govoplan-core.close.bbfa773e")}</Button>}>
      
      <div className="about-logo" />
      <p><strong>i18n:govoplan-core.govoplan_webui.d4ff003b</strong></p>
      <p className="muted">{translateText("i18n:govoplan-core.core_webui_version.a3c761e1")} {packageInfo.version}</p>
      <p>{translateText("i18n:govoplan-core.govoplan_is_a_modular_platform_runner_for_govern.159abeab")}</p>
      <p className="muted">{translateText("i18n:govoplan-core.installed_modules.cd6863dd")} {moduleSummary}</p>
      <p><a href="https://add-ideas.de" target="_blank" rel="noreferrer">add-ideas.de</a></p>
    </Dialog>);

}
