import $ from "jquery";
import { createRoot } from "react-dom/client";
import { hooks } from "rml";

import { locationRestCustomFieldGet } from "../admin.js";
import { Provider } from "../components/provider.js";
import { SeoAttachmentLink } from "../components/seoAttachmentLink.js";
import { request } from "../utils/request.js";

import type { ParamsRestCustomFieldGet, RequestRestCustomFieldGet, ResponseRestCustomFieldGet } from "../admin.js";

function applyCustomField() {
    hooks.register("wprfc/rpm/customField", async function (this: JQuery, { id }: { id: number }) {
        $(this).html('<span class="spinner is-active"></span>');
        const { html } = await request<RequestRestCustomFieldGet, ParamsRestCustomFieldGet, ResponseRestCustomFieldGet>(
            {
                location: locationRestCustomFieldGet,
                params: {
                    id,
                },
            },
        );
        $(this).html(html);

        // SEO single media dialog
        const singleSeoContainer = $(this).find(".rpm-single-seo").get(0);
        singleSeoContainer &&
            createRoot(singleSeoContainer).render(
                <Provider>
                    <SeoAttachmentLink
                        id={id}
                        onOpen={() => $(".media-modal.wp-core-ui").parent().hide()}
                        onClose={() => $(".media-modal.wp-core-ui").parent().show()}
                    />
                </Provider>,
            );
    });
}

export { applyCustomField };
