import { CloseOutlined } from "@ant-design/icons";
import { App, Avatar, Popover } from "antd";
import $ from "jquery";
import { reaction } from "mobx";
import { observer } from "mobx-react";
import { useCallback, useEffect } from "react";

import { Provider as LicenseProvider } from "@devowl-wp/real-product-manager-wp-client";
import { RatingPointer } from "@devowl-wp/real-utils";

import { ConfigLicensingConsumer } from "./licensing/consumer.js";
import { PausedError } from "./pausedError.js";
import { PopupSection } from "./popupSection.js";
import { Provider } from "./provider.js";
import { QueueList } from "./queueList.js";
import { StatusCounter } from "./statusCounter.js";
import { useStores } from "../store/stores.js";
import { Hooks } from "../utils/hooks.js";
import { __ } from "../utils/i18n.js";

import type { ActionPhysicalUpdatedParams } from "../utils/hooks.js";
import type { ComponentProps, FC } from "react";

const DialogButton: FC = observer(() => {
    const { modal, message } = App.useApp();
    const { optionStore, queueStore } = useStores();
    const { isRatable, slug, forcePopupOpen, others, publicUrl } = optionStore;
    const { showLicenseFormImmediate } = others;
    const { pausedError, done } = queueStore;

    const handleCloseIcon = useCallback(() => {
        $(".rpm-popover").addClass("ant-popover-hidden");
        optionStore.dismissFirstTimeQueueNotice();
        optionStore.setAutomaticInfoPanelOpen(false);
    }, [optionStore]);

    useEffect(() => {
        // Show license dialog for the first time
        if ($("body").hasClass("upload-php") && showLicenseFormImmediate && !(window as any).Playwright) {
            const createdModal = modal.info({
                icon: null,
                title: (
                    <>
                        <span>Real Physical Media</span>
                        <Provider app={{ style: { float: "right" } }}>
                            <Avatar src={`${publicUrl}images/logos/real-physical-media.svg`} shape="square" size={30} />
                        </Provider>
                    </>
                ),
                width: 800,
                okButtonProps: {
                    style: { display: "none" },
                },
                cancelButtonProps: {
                    style: { display: "none" },
                },
                maskClosable: false,
                content: (
                    <LicenseProvider>
                        <ConfigLicensingConsumer withinModal />
                    </LicenseProvider>
                ),
            });

            // Automatically close the dialog
            reaction(
                () => others.showLicenseFormImmediate,
                (val) => {
                    if (!val) {
                        createdModal.destroy();
                    }
                },
            );
        }

        // Add item to queue manually when clicking the manual button
        $(document).on("click", "a.rpm-manual-queue", function (e) {
            const $o = $(this);
            const id = +$o.attr("data-id");
            (async () => {
                const hide = message.loading(__("Add file to queue..."));
                try {
                    await queueStore.addItem(id);

                    // Update compat view
                    $o.parents("[data-wprfc]").attr("data-wprfc-visible", 1);
                } catch (e) {
                    message.error((e as any).responseJSON.message);
                } finally {
                    hide();
                }
            })();
            return e.preventDefault();
        });

        // Update compat view also when queue item processed
        Hooks.handler.addAction(
            Hooks.ACTION_PHYSICAL_UPDATED,
            "internal/compatView",
            ({ done: { attachment } }: ActionPhysicalUpdatedParams) => {
                $(`[data-wprfc="rpm/customField"][data-id="${attachment}"]:visible`).attr("data-wprfc-visible", 1);
            },
        );
    }, []);

    // Show rating popup
    isRatable &&
        done.length &&
        new RatingPointer(
            slug,
            $("#admin-bar-rpm").parent(),
            __(
                "<strong>Real Physical Media</strong> just moved a file physically. Do you like it? Do us a favor and rate us.",
            ),
            "rpm-real-utils-bar-pointer",
        );

    const tooltipAttr = {} as ComponentProps<typeof Popover>;
    if (forcePopupOpen) {
        tooltipAttr.visible = true;
    }

    return (
        <span data-done={done.length}>
            <Popover
                trigger="hover"
                mouseEnterDelay={0.1}
                mouseLeaveDelay={0.1}
                overlayClassName="rpm-popover"
                overlayStyle={{ zIndex: 9999 }}
                placement="bottomLeft"
                content={
                    <span>
                        <CloseOutlined onClick={handleCloseIcon} style={{ float: "right" }} />
                        <ul>
                            <li className="rpm-section">{pausedError ? <PausedError /> : <QueueList />}</li>
                            <li className="rpm-section">
                                <PopupSection />
                            </li>
                        </ul>
                    </span>
                }
                {...tooltipAttr}
            >
                <span>
                    <StatusCounter />
                </span>
            </Popover>
        </span>
    );
});

export { DialogButton };
