import $ from "jquery";

import { CUSTOMIZE_CLASS_CHECKBOX } from "./getSanitizedControlValue.js";
import { getSidebarCustomize } from "./getSidebarCustomize.js";
import { hasControlChanged } from "./hasControlChanged.js";

import type { CustomizeIds } from "../types/customizeIds.js";
import type { CustomizeValues } from "../types/customizeValues.js";

/**
 * Make defaults resettable through an UI element.
 */
function makeDefaultsResettable(ids: CustomizeIds, defaults: CustomizeValues) {
    const customize = getSidebarCustomize();

    for (const section in defaults) {
        const settings = defaults[section];
        for (const setting in settings) {
            let defaultValue = settings[setting];

            // MobX observable compatibility
            if (typeof defaultValue.toJS === "function") {
                defaultValue = defaultValue.toJS();
            }

            const controlId = ids.settings[section][setting];
            const controlContainer = customize.control(controlId)?.container as JQuery<HTMLLIElement>;
            if (controlContainer) {
                // Determine top alignment depending on control
                let top = parseInt(controlContainer.css("padding-top"));
                if (controlContainer.hasClass(CUSTOMIZE_CLASS_CHECKBOX)) {
                    top += 9;
                }

                // Create the UI element
                controlContainer.css("position", "relative");
                const button = $(
                    `<button class="button button-small customize-button-reset" style="top:${top}px;">
    <span class="dashicons dashicons-image-rotate"></span>
</button>`,
                )
                    .appendTo(controlContainer)
                    .on("click", (e) => {
                        customize(controlId).set(defaultValue);
                        controlContainer.trigger("customize-reset-value", {
                            defaultValue,
                        });

                        button.hide();
                        e.preventDefault();
                    });

                // Toggle visibility on live changes
                let throttle: ReturnType<typeof setTimeout>;
                const fnToggle = () => {
                    clearTimeout(throttle);
                    throttle = setTimeout(
                        () => button[hasControlChanged(controlId, defaultValue) ? "show" : "hide"](),
                        50,
                    );
                };
                fnToggle();
                customize(controlId, (value: any) => value.bind("change", fnToggle));
            }
        }
    }
}

export { makeDefaultsResettable };
