import { useCallback, useEffect } from "react";

import { getSidebarCustomize, useCustomControl } from "@devowl-wp/customize";
import type { Customize } from "@devowl-wp/react-cookie-banner";

import { RootStore } from "../../../store/stores.js";
import { __ } from "../../../utils/i18n.js";

import type { FC, SelectHTMLAttributes } from "react";

/**
 * This control simply copies the decision option and provides the
 * exact same choices. This control does not hold any value!
 */
const DecisionButtonTypeSelectControl: FC<{
    decision: "acceptAll" | "acceptEssentials" | "acceptIndividual";
}> = ({ decision }) => {
    const { backboneView } = useCustomControl();

    // Obtain value and select choices
    const customize = getSidebarCustomize();
    const settingId = RootStore.get.optionStore.others.customizeIdsBanner.settings.decision[decision];
    const setting = customize(settingId);
    const value = setting.get() as Customize["decision"][typeof decision];
    const options: { [key: string]: string } = {
        button: __("Button"),
        link: __("Link"),
        hide: __("Hide"),
    };

    // Listen for changes and rerender this control
    let skipChange = false;
    useEffect(() => setting.bind("change", () => !skipChange && backboneView.renderContent()), []);

    // Change the setting of the duplicated control
    const handleChange: SelectHTMLAttributes<HTMLSelectElement>["onChange"] = useCallback(
        (e) => {
            skipChange = true;
            setting.set(e.target.value);
            skipChange = false;
            backboneView.renderContent();
        },
        [setting],
    );

    return (
        <select value={value} onChange={handleChange}>
            {Object.keys(options).map((key) => (
                <option key={key} value={key}>
                    {options[key]}
                </option>
            ))}
        </select>
    );
};

export { DecisionButtonTypeSelectControl };
