import { LoadingOutlined } from "@ant-design/icons";
import { Alert, App } from "antd";
import $ from "jquery";
import { observer } from "mobx-react";
import { useCallback, useMemo, useState } from "react";

import { reactNl2Br } from "@devowl-wp/react-utils";

import { SeoDialog } from "./seoDialog.js";
import { useStores } from "../store/stores.js";
import { __ } from "../utils/i18n.js";

import type { FC } from "react";

/**
 * List the available handlers and show a button to install / activate them.
 */
const PopupSection: FC = observer(() => {
    const { message } = App.useApp();
    const { optionStore, seoStore } = useStores();
    const {
        view: { isAutomaticInfoPanelOpen },
        others: { manageOptions, isAutomaticQueueing, supportsAllChildrenSql, isDevLicense },
    } = optionStore;

    const [isAutomaticBusy, setAutomaticBusy] = useState(false);
    const [isSeoModalOpen, setSeoModalOpen] = useState(false);
    const isWpAdmin = useMemo(() => $("body").hasClass("wp-admin"), []);

    /**
     * When the link is clicked and automatic queuing is activate, let
     * the user confirm and deactivate it. If not activated yet, show the automatic box.
     */
    const handleSetAutomaticInfoPanelOpen = useCallback(async () => {
        if (isAutomaticInfoPanelOpen) {
            optionStore.setAutomaticInfoPanelOpen(false);
        } else if (isAutomaticQueueing && window.confirm(__("Are you sure?"))) {
            setAutomaticBusy(true);
            try {
                await optionStore.setIsAutomaticQueueing(false);
            } catch (e) {
                message.error(e.responseJSON.message);
            }
            setAutomaticBusy(false);
        } else {
            optionStore.setAutomaticInfoPanelOpen(true);
        }
    }, [isAutomaticInfoPanelOpen, isAutomaticQueueing, setAutomaticBusy, optionStore]);

    /**
     * Activate automatic queueing.
     */
    const handleAutomaticActivate = useCallback(async () => {
        setAutomaticBusy(true);
        optionStore.setAutomaticInfoPanelOpen(false);
        try {
            await optionStore.setIsAutomaticQueueing(true);
        } catch (e) {
            message.error(e.responseJSON.message);
        }
        setAutomaticBusy(false);
    }, [setAutomaticBusy, setAutomaticBusy, optionStore]);

    const handleSeoModalOpen = useCallback(() => {
        setSeoModalOpen(true);
        seoStore.fetch(true);
        $(".rpm-popover").addClass("ant-popover-hidden");
    }, [setSeoModalOpen, seoStore]);

    const handleSeoModalClose = useCallback(() => setSeoModalOpen(false), [setSeoModalOpen]);

    return (
        <>
            <SeoDialog open={isSeoModalOpen} onClose={handleSeoModalClose} />
            <ul>
                <li className="rpm-headline">{__("Real Physical Media")}</li>
                {isDevLicense && (
                    <Alert
                        type="warning"
                        showIcon
                        message={
                            <>
                                {__("Product license not for production use!")} (
                                <a
                                    href={__("https://devowl.io/knowledge-base/license-installation-type/")}
                                    rel="noreferrer"
                                    target="_blank"
                                >
                                    {__("Learn more")}
                                </a>
                                )
                            </>
                        }
                        style={{ margin: 10 }}
                    />
                )}
                {!isAutomaticInfoPanelOpen ? (
                    <>
                        {!!manageOptions && (
                            <li>
                                <a onClick={handleSetAutomaticInfoPanelOpen}>
                                    {isAutomaticBusy && <LoadingOutlined spin />}
                                    {isAutomaticQueueing
                                        ? __("Deactivate automatic queueing")
                                        : __("Activate automatic change detection")}
                                </a>
                                &nbsp;&middot;&nbsp;
                                {isWpAdmin && (
                                    <span>
                                        <a onClick={handleSeoModalOpen}>{__("SEO Redirects")}</a>
                                        &nbsp;&middot;&nbsp;
                                    </span>
                                )}
                                <a href={`${manageOptions}#rml-rpm-handlers`}>{__("Settings")}</a>
                            </li>
                        )}
                    </>
                ) : (
                    <li className="rpm-automatic-box">
                        <strong>{__("Activate automatic change detection")}</strong>
                        {supportsAllChildrenSql ? (
                            <span>
                                <p>
                                    {reactNl2Br(
                                        __(
                                            'Real Physical Media can automatically detect when you have moved a file to the Real Media Library and can also move it physically in your file system.\n\nBefore you enable this feature, go to the "Attachment Details" or "Edit Media" dialog of the file you last moved and click the "Move physically" button. Then check that the file is available at the new URL as expected.\n\nWe recommend that you perform this manual check before you enable automatic moving, because special WordPress configurations rarely result in errors with the Media File Renamer handler.',
                                        ),
                                    )}
                                </p>
                                <br />
                                <a className="button button-primary" onClick={handleAutomaticActivate}>
                                    {__("Activate")}
                                </a>
                                <br />
                            </span>
                        ) : (
                            <p>
                                {__(
                                    "Unfortunately, you cannot activate automatic change detection. Your current database system does not support some mandatory functions. Please update your MySQL/MariaDB database to the latest version. Technical reason: Your database system does not allow you to read from a hierarchical query created by wp_rml_create_all_children_sql().",
                                )}
                            </p>
                        )}
                        <br />
                        <a onClick={handleSetAutomaticInfoPanelOpen}>{__("Back")}</a>
                    </li>
                )}
            </ul>
        </>
    );
});

export { PopupSection };
