import { Switch } from "antd";
import { useCallback, useState } from "react";

import { ProTag } from "./proTag.js";
import { useStores } from "../store/stores.js";
import { __ } from "../utils/i18n.js";

import type { ComponentProps, FC } from "react";

const ListTableTreeSwitch: FC = () => {
    const [busy, setBusy] = useState(false);
    const { optionStore } = useStores();
    const {
        others: { isAvailable, isPro, typenow, canManageOptions },
    } = optionStore;

    let disabledPro = false;

    const handleToggle: ComponentProps<typeof Switch>["onChange"] = useCallback(
        async (state) => {
            setBusy(true);
            await optionStore.updatePostTypeOptions(typenow, {
                active: state,
            });
            window.location.reload();
        },
        [typenow, optionStore],
    );

    if (!canManageOptions) {
        return null;
    }

    // Always advertise "Page" taxonomy in lite version
    if (!isPro && typenow !== "post") {
        disabledPro = true;
    } else if (!isAvailable) {
        return null;
    }

    return (
        <div style={{ paddingTop: 3 }}>
            <Switch disabled={disabledPro} onChange={handleToggle} loading={busy} />
            <div style={{ float: "right", padding: disabledPro ? "0px 10px" : "2px 10px" }}>
                {__("Enable category tree")}{" "}
                {disabledPro && <ProTag feature={typenow === "page" ? "page-tree" : "cpt-tree"} />}
            </div>
        </div>
    );
};

export { ListTableTreeSwitch };
