import { useAdminContext } from "@insite/shell/Components/Shell/AdminContext";
import { AdminOptions } from "@insite/shell/Services/AdminService";

interface damImage {
    alt?: unknown;
    guid: string;
    height: number;
    title: string;
    type: string;
    url: string;
    width: number;
}

let currentOnFileSelected = (url: string) => {};
let optiDamUrl = "";

const fileSelected = (event: any) => {
    if (event.origin !== optiDamUrl || !Array.isArray(event.data)) {
        return;
    }
    const selectedImage = event.data[0] as damImage;
    currentOnFileSelected(selectedImage.url);
};

window.addEventListener("message", fileSelected, false);

type parameter = {
    onFileSelected: (url: string) => void;
    onClose: () => void;
};

export const openDam = ({ onFileSelected, onClose, options }: parameter & { options: AdminOptions }) => {
    optiDamUrl = options.optiDam.url;
    return {
        openFileBrowser: () => {
            currentOnFileSelected = url => {
                onClose();
                onFileSelected(url);
            };

            const encodedOptions = window.btoa(
                JSON.stringify({
                    organization: options.optiDam.organizationId,
                }),
            );

            const damWindow = window.open(
                `${options.optiDam.url}/cloud/library-picker?pickerOptions=${encodedOptions}`,
                "Library",
                "popup",
            );

            const pollWindowClosed = () => {
                if (damWindow!.closed) {
                    onClose();
                } else {
                    requestAnimationFrame(pollWindowClosed);
                }
            };
            pollWindowClosed();
        },
    };
};

export const useFileBrowser = ({ onFileSelected, onClose }: parameter) => {
    const { options } = useAdminContext();

    if (options.optiDam.isEnabled) {
        return openDam({ onFileSelected, onClose, options });
    }

    return {
        openFileBrowser: () => {
            (window as any).CKFinder.modal({
                chooseFiles: true,
                chooseFilesClosePopup: true,
                resizeImages: false,
                resourceType: "UserFiles",
                onInit(finder: any) {
                    document.getElementById("ckf-modal-close")?.addEventListener("click", onClose);

                    finder.on("files:choose", (event: any) => {
                        onClose();
                        onFileSelected(event.data.files.first().getUrl());
                    });
                },
                plugins: ["SearchFolder"],
            });
        },
    };
};
