import {
    AreaChartOutlined,
    KeyOutlined,
    PictureOutlined,
    RightOutlined,
    ScanOutlined,
    SettingOutlined,
} from "@ant-design/icons";
import { App, Layout, Menu, Spin } from "antd";
import $ from "jquery";
import { observer } from "mobx-react";
import { useCallback, useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import Modal from "react-responsive-modal";

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

import { AnalyseContent } from "./analyse.js";
import { ConfigLicensingConsumer } from "./licensing/consumer.js";
import { RegenerateContent } from "./regenerate.js";
import { SettingsContent } from "./settings.js";
import { SingleFileContent } from "./singleFile.js";
import { SingleFile } from "../models/singleFile.js";
import { useStores } from "../store/stores.js";
import { __ } from "../utils/i18n.js";

import type { MouseEvent, ReactText } from "react";

const { Sider, Content, Header } = Layout;

const Z_INDEX = 160001;
const MESSAGE_SUCCESSFUL_REGENERATION_KEY = "rtg-successful-regeneration";

/**
 * The dialog button opens and closes the dialog with tabs and content.
 *
 * It automatically creates a button in media library through ReactDOM.
 */
const DialogButton = observer(() => {
    const { message } = App.useApp();
    const stores = useStores();
    const { statsStore, optionStore, attachmentsStore } = stores;
    const {
        unimplemented,
        others: { canManageOptions, showLicenseFormImmediate, isDevLicense },
    } = optionStore;
    const { regenerateBusy, analyzeBusy, singleBusy, single } = attachmentsStore;
    const [isOpen, setOpen] = useState(false);
    const [selectedTab, setSelectedTab] = useState("analyse");
    const doesCurrentlyProcess = isOpen && (regenerateBusy || analyzeBusy || singleBusy);
    const unloadText = __("Are you sure you want to cancel the current process?");
    const showLicenseFormImmediateCurrentUser =
        showLicenseFormImmediate && canManageOptions && !(window as any).Playwright;

    const openSingleById = useCallback((id: number) => {
        attachmentsStore.fetchSingle(id);
        setOpen(true);
        setSelectedTab("single");
    }, []);

    const handleSelect = useCallback(
        ({ key }: { key: ReactText }) => {
            const useKey = key as string;
            setSelectedTab(useKey);
            ["analyse", "generate"].indexOf(useKey) > -1 && statsStore.fetch();
            // key === "single" && self.single && fetchSingle(self.single.id); // Refresh single
        },
        [stores],
    );

    const handleAnalyseItemClick = useCallback(
        (e: MouseEvent<HTMLLIElement, globalThis.MouseEvent>) =>
            openSingleById($(e.target).data().id || $(e.target).parents("li").data().id),
        [],
    );

    /**
     * Create the buttons and listeners once for regeneration and dialog openers.
     */
    useEffect(() => {
        statsStore.fetch();

        // General "Thumbnails" button in media library
        const $body = $("body");
        if ($body.hasClass("wp-admin") && $body.hasClass("upload-php")) {
            const buttonPlaceholder = $("<span></span>").insertAfter($(".wp-heading-inline").next("a:last"));
            createRoot(buttonPlaceholder.get(0)).render(
                <button className="add-new-h2" onClick={() => setOpen(true)}>
                    {__("Regenerate Thumbnails")}
                </button>,
            );
        }

        // Listeners for "Info" in attachment detail / row
        $(document).on("click", 'button[data-rtg][data-action="info"]', function (e) {
            openSingleById(+$(this).data("rtg"));
            return e.preventDefault();
        });

        // Listeners for "Regenerate" in attachment detail / row
        $(document).on(
            "click",
            'button[data-rtg][data-action="regenerate"], a[data-rtg][data-action="regenerate"]',
            async function () {
                const $elem = $(this);
                $elem.prop("disabled", true).stop().fadeTo(100, 0.3);
                await new SingleFile({
                    id: +$elem.data("rtg"),
                }).regenerate(false, true);
                $elem.prop("disabled", false).stop().fadeTo(100, 1);

                message.destroy(MESSAGE_SUCCESSFUL_REGENERATION_KEY);
                message.success({
                    key: MESSAGE_SUCCESSFUL_REGENERATION_KEY,
                    content: __("Successfully regenerated image!"),
                });
            },
        );

        // Check hash and automatically open thumbnails dialog
        if (window.location.search.indexOf("thumbnails=true") > -1) {
            setOpen(true);
            window.history.replaceState({}, document.title, window.location.href.replace("thumbnails=true", ""));
        }
    }, []);

    return (
        <Modal
            open={isOpen}
            onClose={() => {
                if ((doesCurrentlyProcess && window.confirm(unloadText)) || !doesCurrentlyProcess) {
                    setOpen(false);
                }
            }}
            center
            styles={{
                root: {
                    zIndex: Z_INDEX,
                },
                overlay: { zIndex: Z_INDEX },
                modal: {
                    padding: 0,
                    width: 1200,
                    maxWidth: "initial",
                    marginTop: 32,
                    zIndex: Z_INDEX,
                    height: "calc(100vh - 105px)",
                },
            }}
        >
            <Layout hasSider style={{ minHeight: "100%" }}>
                <Sider breakpoint="lg" collapsedWidth="0">
                    <Menu
                        theme="dark"
                        mode="inline"
                        selectedKeys={[selectedTab]}
                        onSelect={handleSelect}
                        items={[
                            {
                                key: "analyse",
                                disabled: regenerateBusy || showLicenseFormImmediateCurrentUser,
                                icon: <AreaChartOutlined />,
                                label: (
                                    <>
                                        <span className="nav-text">{__("Analyze")}</span>
                                        <Spin
                                            style={{ float: "right", marginTop: 10 }}
                                            spinning={statsStore.busy && selectedTab === "analyse"}
                                            size="small"
                                        />
                                    </>
                                ),
                            },
                            {
                                key: "generate",
                                disabled: analyzeBusy || showLicenseFormImmediateCurrentUser,
                                icon: <ScanOutlined />,
                                "data-id": "rtg-dialog-menu-item-regenerate",
                                label: (
                                    <>
                                        <span className="nav-text">{__("Bulk regenerate")}</span>
                                        <Spin
                                            style={{ float: "right", marginTop: 10 }}
                                            spinning={statsStore.busy && selectedTab === "generate"}
                                            size="small"
                                        />
                                    </>
                                ),
                            },
                            {
                                key: "single",
                                disabled: showLicenseFormImmediateCurrentUser,
                                icon: <PictureOutlined />,
                                label: (
                                    <>
                                        <span className="nav-text">{__("Single file")}</span>
                                        <Spin
                                            style={{ float: "right", marginTop: 10 }}
                                            spinning={singleBusy || !!single?.busy}
                                            size="small"
                                        />
                                        {!single?.busy && single?.thumbnail && (
                                            <img className="rtg-dialog-single-preview" src={single.thumbnail} />
                                        )}
                                    </>
                                ),
                            },
                            canManageOptions && {
                                key: "settings",
                                disabled: showLicenseFormImmediateCurrentUser,
                                icon: <SettingOutlined />,
                                "data-id": "rtg-dialog-menu-item-settings",
                                label: <span className="nav-text">{__("Settings")}</span>,
                            },
                            canManageOptions && {
                                key: "license",
                                disabled: showLicenseFormImmediateCurrentUser,
                                icon: <KeyOutlined />,
                                label: <span className="nav-text">{__("Licensing")}</span>,
                            },
                        ].filter(Boolean)}
                    />
                    {unimplemented.length > 0 && (
                        <div className="notice inline notice-error notice-alt" style={{ margin: "0 0 10px" }}>
                            <p>
                                {__("You have activated the plugin")} <strong>{unimplemented.join(", ")}</strong>.{" "}
                                {__(
                                    "The plugin influenced how thumbnails are generated or can cause costs for each newly generated thumbnail. Use the thumbnail regenerate feature with caution!",
                                )}
                                .
                            </p>
                        </div>
                    )}
                    {isDevLicense && (
                        <div className="notice inline notice-warning notice-alt" style={{ margin: "0 0 10px" }}>
                            <p>
                                {__("Product license not for production use!")} (
                                <a
                                    href={__("https://devowl.io/knowledge-base/license-installation-type/")}
                                    rel="noreferrer"
                                    target="_blank"
                                >
                                    {__("Learn more")}
                                </a>
                                )
                            </p>
                        </div>
                    )}
                </Sider>
                {showLicenseFormImmediateCurrentUser ? (
                    <LicenseProvider>
                        <div style={{ padding: "30px 20px" }}>
                            <ConfigLicensingConsumer />
                        </div>
                    </LicenseProvider>
                ) : (
                    <>
                        {selectedTab === "analyse" && <AnalyseContent onClick={handleAnalyseItemClick} />}
                        {selectedTab === "generate" && <RegenerateContent onClick={handleAnalyseItemClick} />}
                        {selectedTab === "single" && <SingleFileContent />}
                        {selectedTab === "settings" && !!canManageOptions && <SettingsContent />}
                        {selectedTab === "license" && !!canManageOptions && (
                            <LicenseProvider>
                                <Layout>
                                    <Header style={{ background: "#fff" }}>
                                        {__("Thumbnails")} <RightOutlined /> {__("Licensing")}
                                    </Header>
                                    <Content style={{ margin: "24px 16px 0" }}>
                                        <ConfigLicensingConsumer />
                                    </Content>
                                </Layout>
                            </LicenseProvider>
                        )}
                    </>
                )}
            </Layout>
        </Modal>
    );
});

export { DialogButton };
