import { useCallback } from "react";

import { Dropdown, Icon, Menu } from "@devowl-wp/react-folder-tree";

import { useStores } from "../store/stores.js";

/**
 * Create a tax switcher if more than one taxonomy is available for the post type.
 */
const TaxSwitcher = ({ disabled }: { disabled: boolean }) => {
    if (process.env.PLUGIN_CTX === "pro") {
        const { optionStore } = useStores();
        const {
            others: { taxos, taxnow },
        } = optionStore;
        const handleTaxSwitch = useCallback(({ key }: { key: string }) => optionStore.setTaxnow(key), [optionStore]);

        const keys = Object.keys(taxos);
        if (keys.length < 1) {
            return null;
        }

        // Create tax switcher overlay
        const overlayMenu = keys.map((key) => {
            const label = taxos[key];
            return <Menu.Item key={key}>{label}</Menu.Item>;
        });
        const overlay = (
            // @ts-expect-error outdated @types/react
            <Menu selectedKeys={[taxnow]} onClick={handleTaxSwitch}>
                {overlayMenu}
            </Menu>
        );

        return (
            // @ts-expect-error outdated @types/react
            <Dropdown placement="bottomRight" overlay={overlay} disabled={disabled}>
                <a className="ant-dropdown-link" style={{ textDecoration: "none", cursor: "pointer" }}>
                    {taxos[taxnow]} <Icon type="down" />
                </a>
            </Dropdown>
        );
    } else {
        return null;
    }
};

export { TaxSwitcher };
