import "../../style/controls/presetSelector.scss";

import { observer } from "mobx-react";
import { useEffect, useState } from "react";

import { SameSectionAccordion } from "@devowl-wp/customize";
import { waitObject } from "@devowl-wp/react-utils";

import { CustomizePresetCard } from "./presetCard.js";
import { BannerPreset } from "../../models/bannerPreset.js";
import { useStores } from "../../store/stores.js";
import { __ } from "../../utils/i18n.js";

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

const INTERVAL_SWITCH_INDIVIDUAL_PRIVACY_SECONDS = 5;

const CustomizePresetSelector: FC = observer(() => {
    const [open, setOpen] = useState(false);
    const [fetched, setFetched] = useState(false);
    const { customizeBannerStore } = useStores();
    const { busyPresets, presets } = customizeBannerStore;

    const handleToggle: ComponentProps<typeof SameSectionAccordion>["onToggle"] = (state) => {
        if (state && !fetched) {
            customizeBannerStore.fetchPresets();
            setFetched(true);
        }
        setOpen(state);
    };

    const handleApply = () => {
        handleToggle(false);
    };

    // Also, allow autofocus by a customAutofocus (this is not a standard!)
    useEffect(() => {
        if (window.location.href.indexOf("customAutofocus[rcb-presets]=1") > -1) {
            // We need to wait for the iframe so the presets can be applied to the cookie banner
            waitObject(() => BannerPreset.getIframeStore()).then(() => handleToggle(true));
        }
    }, []);

    return (
        <SameSectionAccordion
            state={open}
            onToggle={handleToggle}
            title={
                <>
                    <span className={busyPresets ? "spinner is-active" : ""} style={{ margin: 0 }}></span>{" "}
                    {__("Presets")}
                </>
            }
            grouped
        >
            <p className="description">
                {__(
                    "You can choose between different presets. Presets only change the style, but no texts or content. Tip: Hover the mouse over a preset to see a real-time preview. Wait %d seconds, and you will see a preview of the individual privacy settings screen.",
                    INTERVAL_SWITCH_INDIVIDUAL_PRIVACY_SECONDS,
                )}
            </p>
            <br />
            {Array.from(presets.values()).map((preset) => (
                <CustomizePresetCard key={preset.id} preset={preset} onApply={handleApply} />
            ))}
        </SameSectionAccordion>
    );
});

export { INTERVAL_SWITCH_INDIVIDUAL_PRIVACY_SECONDS, CustomizePresetSelector };
