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

import { formServiceAttributesFromTemplate } from "@devowl-wp/react-cookie-banner-admin";
import type { ClientServiceTemplate } from "@devowl-wp/service-cloud-consumer";

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

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

const BlockerFormNoticeNoneExistingCookies: FC<{
    nonExistingServices: ClientServiceTemplate["use"][];
    onCreated: ComponentProps<typeof CookieEditForm>["onCreated"];
}> = observer(({ nonExistingServices, onCreated }) => {
    const [openId, setOpenId] = useState<string>();
    const groups = useStores().cookieStore.groups.sortedGroups.map(({ data: { id, name } }) => ({ id, name }));

    // Created templates to hide them from the list
    const [created, setCreated] = useState<string[]>([]);
    const useNoneExistingCookies = (nonExistingServices || []).filter(
        ({ identifier }) => created.indexOf(identifier) === -1,
    );

    // 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 = nonExistingServices?.map((template) => {
        const { identifier, version } = template;
        return (
            <Modal
                key={identifier}
                open={openId === identifier}
                title={__("Add service")}
                width="calc(100% - 50px)"
                bodyStyle={{ paddingBottom: 0 }}
                footer={null}
                onCancel={() => setOpenId(undefined)}
            >
                <CookieEditForm
                    overwriteAttributes={formServiceAttributesFromTemplate(template, { groups })}
                    navigateAfterCreation={false}
                    scrollToTop={false}
                    template={{ identifier, version }}
                    onCreated={(model) => {
                        setOpenId(undefined);
                        setCreated([...created, openId]);
                        onCreated(model);
                    }}
                />
            </Modal>
        );
    });

    return (
        <>
            {modalWindows}
            {useNoneExistingCookies.length === 0 ? null : (
                <div className="notice notice-warning below-h2 notice-alt">
                    <p>
                        {__(
                            "Some services from the template could not be found. Please select (or create if not already exist) the following services:",
                            useNoneExistingCookies.join(", "),
                        )}
                    </p>
                    <ul style={{ margin: "0 0 10px" }}>
                        {useNoneExistingCookies.map(({ identifier, name, subHeadline }) => (
                            <li key={identifier}>
                                <strong>
                                    {name}
                                    {subHeadline ? ` (${subHeadline})` : ""}
                                </strong>
                                &nbsp;&bull;&nbsp;
                                <a
                                    onClick={(e) => {
                                        setOpenId(identifier);
                                        e.preventDefault();
                                    }}
                                >
                                    {__("Create now")}
                                </a>
                            </li>
                        ))}
                    </ul>
                </div>
            )}
        </>
    );
});

export { BlockerFormNoticeNoneExistingCookies };
