import * as React from "react";
import type tinymce from "tinymce";
import { createRoot } from "@wordpress/element";
import { TitleDialog } from "../components/title-dialog/TitleDialog";
import { JustwatchProvider } from "../context/context";
import { TitleSelection } from "../types";
import { generateShortcode } from "@/block/save";

// Declare tinyMCE on the window interface
declare global {
    interface Window {
        tinyMCE: typeof tinymce
    }
}

export const TITLE_DIALOG_ROOT_ID = "jw-title-dialog-root";

document.addEventListener("DOMContentLoaded", function () {
    if (!window.tinyMCE) {
        return;
    }
    window.tinyMCE.PluginManager.add("justwatch", function (editor) {
        let modalContainer = document.getElementById(TITLE_DIALOG_ROOT_ID);
        const { settings, pluginUrl } = window.justwatch;

        if (!modalContainer) {
            modalContainer = document.createElement("div");
            modalContainer.id = TITLE_DIALOG_ROOT_ID;
        }
        // Create a root for the React component
        const root = createRoot(modalContainer);

        const render = (jsx: React.ReactNode) => {
            root.render(
                <JustwatchProvider {...settings}>{jsx}</JustwatchProvider>
            );
        };
        // Function to close the modal and remove the root node
        const closeModal = () => {
            render(<></>);
        };

        const handleConfirm = (titleSelection: TitleSelection | undefined): void => {
            if (!titleSelection) return;
            const str = generateShortcode(titleSelection);
            editor.insertContent(`&nbsp;${str}&nbsp;`); // Insert text into the editor
            closeModal(); // Close the modal after confirming
        };

        // Function to render the modal using React
        const openModal = () => {
            // Use React to render the modal
            render(
                <TitleDialog
                    isOpen={true}
                    onClose={closeModal}
                    onConfirm={handleConfirm} // Pass handleConfirm to the modal
                />
            );
        };

        // Add command to open the modal
        editor.addCommand("openJustwatchModal", () => {
            openModal();

            return true;
        });

        // Add the button to the TinyMCE toolbar
        editor.addButton("justwatch", {
            // text: "Justwatch",
            cmd: "openJustwatchModal", // Use command to open modal
            image : pluginUrl + '/../img/justwatch-icon.png',
        });

        return {
            getMetadata: () => ({
                name: "JustWatch",
                url: "https://justwatch.com",
            }),
        };
    });
});

