import { Modal } from "antd";
import { useEffect, useState } from "react";

import { ErrorModalList } from "./list.js";
import { useStatusErrors } from "../../hooks/useStatusErrors.js";
import { __ } from "../../utils/i18n.js";

import type { FC } from "react";

const ErrorModal: FC = () => {
    const { errors } = useStatusErrors();
    const [visible, setVisible] = useState(false);

    useEffect(() => {
        const { activeElement } = document;
        const hasErrors = Object.values(errors).length > 0;

        if (hasErrors) {
            if (
                activeElement &&
                (/^(?:input|select|textarea|button)$/i.test(activeElement.nodeName) ||
                    activeElement.hasAttribute("contenteditable"))
            ) {
                setVisible(false);

                const listener = () => {
                    setVisible(true);
                };
                activeElement.addEventListener("blur", listener, {
                    once: true,
                });

                return () => {
                    activeElement.removeEventListener("blur", listener);
                };
            } else {
                setVisible(true);
            }
        } else {
            setVisible(false);
        }

        return () => {
            // Silence is golden.
        };
    }, [errors]);

    return (
        <Modal
            className="real-queue-error-modal"
            footer={null}
            title={__("Background tasks: Something went wrong")}
            open={visible}
            width={750}
            closable={false}
        >
            <>
                <p className="description">
                    {__(
                        "Your WordPress installation is working in the background on tasks that you basically don't notice. Unfortunately, an error occurred while running a task. Below is a list of failed tasks that you can either delete (and thus cancel the task) or try again.",
                    )}
                </p>
                <ErrorModalList list={errors} />
            </>
        </Modal>
    );
};

export { ErrorModal };
