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

import type { useFormContentBlockerHandler } from "@devowl-wp/react-cookie-banner-admin";

import { useStores } from "../../../store/stores.js";
import { __ } from "../../../utils/i18n.js";
import { TcfVendorConfigurationForm } from "../cookies/tcf/form.js";

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

const BlockerFormNoticeNoneExistingTcfVendors: FC<{
    nonExistingTcfVendors: ReturnType<typeof useFormContentBlockerHandler>["nonExistingTcfVendors"];
    onCreated: ComponentProps<typeof TcfVendorConfigurationForm>["onCreated"];
}> = observer(({ nonExistingTcfVendors, onCreated }) => {
    const [openId, setOpenId] = useState<number>();
    const { tcfStore } = useStores();
    const { vendorListVersion, vendors } = tcfStore;

    // Created vendors to hide them from the list
    const [created, setCreated] = useState<number[]>([]);
    const useNoneExistingTcfVendors = (nonExistingTcfVendors || []).filter(
        ({ vendorId }) => created.indexOf(vendorId) === -1,
    );

    // Initially fetch all vendors so we can create the modals correctly
    useEffect(() => {
        if (nonExistingTcfVendors.length > 0 && !vendorListVersion) {
            tcfStore.fetchVendors();
        }
    }, [nonExistingTcfVendors, vendorListVersion]);

    if (!vendorListVersion && nonExistingTcfVendors.length > 0) {
        return <Spin spinning />;
    }

    // Create modal windows as they should always be available in React tree (avoid "Can't perform a React state update on an unmounted component")
    const modalWindows = nonExistingTcfVendors?.map(({ vendorId }) => {
        return (
            <Modal
                key={vendorId}
                open={openId === vendorId}
                title={__("Add TCF vendor configuration")}
                width="calc(100% - 50px)"
                bodyStyle={{ paddingBottom: 0 }}
                footer={null}
                onCancel={() => setOpenId(undefined)}
            >
                <TcfVendorConfigurationForm
                    navigateAfterCreation={false}
                    scrollToTop={false}
                    vendor={vendors.get(`${vendorId}`)}
                    onCreated={(model) => {
                        setOpenId(undefined);
                        setCreated([...created, openId]);
                        onCreated(model);
                    }}
                />
            </Modal>
        );
    });

    return (
        <>
            {modalWindows}
            {useNoneExistingTcfVendors.length === 0 ? null : (
                <div className="notice notice-warning below-h2 notice-alt">
                    <p>
                        {__(
                            "Some TCF vendors from the template could not be found. Please select (or create if not already exist) the following TCF vendors:",
                            useNoneExistingTcfVendors.join(", "),
                        )}
                    </p>
                    <ul style={{ margin: "0 0 10px" }}>
                        {useNoneExistingTcfVendors.map(({ vendorId, createAdNetwork }) => (
                            <li key={vendorId}>
                                <strong>{vendors.get(`${vendorId}`).data.name}</strong>
                                &nbsp;&bull;&nbsp;
                                <a
                                    onClick={(e) => {
                                        if (createAdNetwork) {
                                            window.location.href = `#/cookies/tcf-vendors/new?adNetwork=${encodeURIComponent(
                                                createAdNetwork,
                                            )}`;
                                        } else {
                                            setOpenId(vendorId);
                                        }
                                        e.preventDefault();
                                    }}
                                >
                                    {__("Create now")}
                                </a>
                            </li>
                        ))}
                    </ul>
                </div>
            )}
        </>
    );
});

export { BlockerFormNoticeNoneExistingTcfVendors };
