import { Popover, Spin, Tabs } from "antd";
import { observer } from "mobx-react";
import { useCallback, useEffect, useState } from "react";
import { Outlet, useLocation, useNavigate, useParams } from "react-router-dom";

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

import { CookieGroupEditForm } from "./form.js";
import { CookieGroupTabHeadline } from "./tabHeadline.js";
import { useCookieGroupTabSortable } from "../../../../hooks/useCookieGroupTabSortable.js";
import { useStores } from "../../../../store/stores.js";
import { __ } from "../../../../utils/i18n.js";
import { ConfigHintModal } from "../../hintModal.js";

import type { FC } from "react";

const CookieGroupsTabLayout: FC = observer(() => {
    const { cookieStore, optionStore } = useStores();
    const {
        essentialGroup,
        groups: { sortedGroups },
    } = cookieStore;
    const params = useParams();
    const { pathname } = useLocation();
    const isTcfRoute = pathname.indexOf("tcf-vendors") > -1;
    const [isAddNewVisible, setIsAddNewVisible] = useState(false);
    const tab = (isTcfRoute ? "tcf-vendors" : params.cookieGroup) || essentialGroup?.key.toString();
    const isRootQuery = isTcfRoute ? false : !params.cookieGroup;
    const navigate = useNavigate();
    const { isBannerActive, isOnlyRcbCookieCreated, isTcf } = optionStore;
    const { groups } = cookieStore;
    const ref = useCookieGroupTabSortable(!isRootQuery);

    const redirectToEssentialGroupIfRoot = useCallback(() => {
        // Initially replace current url when fetching root instead of "Essential"
        if (isRootQuery && essentialGroup) {
            navigate(isTcf ? "tcf-vendors" : essentialGroup.key.toString(), { replace: true });
        }
    }, [isRootQuery, essentialGroup, isTcf]);

    useAsyncEffect(
        async ({ aborted }) => {
            if (!essentialGroup) {
                await cookieStore.fetchGroups();

                if (!aborted()) {
                    redirectToEssentialGroupIfRoot();
                }
            }
        },
        [essentialGroup, redirectToEssentialGroupIfRoot, isTcf],
    );

    // Avoid flickering when we click the "Cookies" tab again
    useEffect(() => {
        redirectToEssentialGroupIfRoot();
    }, [redirectToEssentialGroupIfRoot]);

    return isRootQuery || sortedGroups.length === 0 ? (
        <Spin style={{ margin: "auto", marginTop: 15 }} />
    ) : (
        <Spin spinning={groups.busy}>
            <div ref={ref}>
                {!isBannerActive && !isOnlyRcbCookieCreated && (
                    <div className="notice notice-warning inline below-h2 notice-alt" style={{ margin: "10px 0 0 0" }}>
                        <p>
                            {__(
                                "The cookie banner is globally deactivated in the settings and is therefore not displayed on your website.",
                            )}{" "}
                            &bull; <a href="#/settings">{__("Enable now")}</a>
                        </p>
                    </div>
                )}
                <Tabs
                    destroyInactiveTabPane
                    activeKey={tab}
                    tabBarExtraContent={
                        ["tcf-vendors"].indexOf(tab) === -1 && (
                            <Popover
                                open={isAddNewVisible}
                                content={<CookieGroupEditForm onClose={() => setIsAddNewVisible(false)} />}
                                placement="bottomRight"
                            >
                                <button
                                    className="button button-primary button-large"
                                    style={{ marginTop: 6 }}
                                    onClick={() => setIsAddNewVisible(!isAddNewVisible)}
                                >
                                    {__("Add group")}
                                </button>
                            </Popover>
                        )
                    }
                    onTabClick={(key: string) => {
                        navigate(`/cookies/${key}`);
                    }}
                    items={[
                        isTcf && {
                            key: "tcf-vendors",
                            label: __("TCF Vendors"),
                            children: (
                                <>
                                    <Outlet />
                                    <ConfigHintModal identifier="tcf-vendor" />
                                </>
                            ),
                        },
                        isTcf && {
                            key: "tcf-vendors-split",
                            label: <span>&bull;</span>,
                            disabled: true,
                            children: <div />,
                        },
                        ...sortedGroups.map((group) => ({
                            key: group.key.toString(),
                            label: <CookieGroupTabHeadline group={group} />,
                            children: (
                                <>
                                    <Outlet />
                                    <ConfigHintModal identifier="cookie" />
                                </>
                            ),
                        })),
                    ].filter(Boolean)}
                />
            </div>
        </Spin>
    );
});

export { CookieGroupsTabLayout };
