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

import { createCookiePolicyTable } from "@devowl-wp/react-cookie-banner";

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

import type { Consent } from "../../../../models/consent.js";
import type { FC } from "react";

const ConsentTableRecordCookiePolicy: FC<{ record: Consent }> = observer(({ record }) => {
    const [isOpen, setIsOpen] = useState(false);
    const { cookiePolicy } = record.revision.data;
    const ref = useRef<HTMLDivElement>();

    // Deactivate TOC links in preview
    useEffect(() => {
        if (isOpen && ref.current) {
            ref.current
                .querySelectorAll<HTMLTableElement>(".devowl-wp-react-cookie-banner-cookie-policy")
                .forEach(createCookiePolicyTable);

            ref.current.querySelectorAll<HTMLAnchorElement>(`a[href^="#"]`).forEach((link) => {
                link.style.cursor = "not-allowed";
                link.addEventListener("click", (e) => e.preventDefault());
            });
        }
    }, [isOpen]);

    return cookiePolicy ? (
        <>
            <Divider>{__("Cookie policy as at the time of consent")}</Divider>
            <p className="description">
                {__(
                    "Use the button below to see what the content of the cookie policy looked like at the time of the user's consent. Styles, e.g. from your theme, which may have influenced the cookie policy page, are not taken into account.",
                )}
            </p>
            <Modal
                title={__("Cookie policy as at the time of consent")}
                open={isOpen}
                onCancel={() => setIsOpen(false)}
                cancelText={__("Close")}
                okButtonProps={{ style: { display: "none" } }}
                width="calc(100% - 50px)"
                destroyOnClose
            >
                <div ref={ref} style={{ marginTop: 35 }} dangerouslySetInnerHTML={{ __html: cookiePolicy }} />
            </Modal>
            <button className="button button-large" onClick={() => setIsOpen(true)}>
                {__("Open cookie policy content")}
            </button>
        </>
    ) : null;
});

export { ConsentTableRecordCookiePolicy };
