import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState } from "react";
import { App, Checkbox, Table } from "antd";
import { uniq } from "lodash";
import { useTranslation } from "react-i18next";
import { useAPIClient, useRequest } from "../../../api-client/index.mjs";
import { useRecord } from "../../../record-provider/index.mjs";
import { useStyles } from "../style.mjs";
import { useMenuItems } from "./MenuItemsProvider.mjs";
const findUids = (items)=>{
    if (!Array.isArray(items)) return [];
    const uids = [];
    for (const item of items){
        uids.push(item.uid);
        uids.push(...findUids(item.children));
    }
    return uids;
};
const getParentUids = function(tree, func) {
    let path = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : [];
    if (!tree) return [];
    for (const data of tree){
        path.push(data.uid);
        if (func(data)) return path;
        if (data.children) {
            const findChildren = getParentUids(data.children, func, path);
            if (findChildren.length) return findChildren;
        }
        path.pop();
    }
    return [];
};
const getChildrenUids = function() {
    let data = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : [], arr = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : [];
    for (const item of data){
        arr.push(item.uid);
        if (item.children && item.children.length) getChildrenUids(item.children, arr);
    }
    return arr;
};
const MenuConfigure = ()=>{
    const { styles } = useStyles();
    const record = useRecord();
    const api = useAPIClient();
    const { message } = App.useApp();
    const { items } = useMenuItems();
    const { t } = useTranslation();
    const allUids = findUids(items);
    const [uids, setUids] = useState([]);
    const { loading, refresh } = useRequest({
        resource: 'roles.menuUiSchemas',
        resourceOf: record.name,
        action: 'list',
        params: {
            paginate: false
        }
    }, {
        onSuccess (data) {
            var _data_data;
            setUids((null == data ? void 0 : null == (_data_data = data.data) ? void 0 : _data_data.map((schema)=>schema['x-uid'])) || []);
        }
    });
    const resource = api.resource('roles.menuUiSchemas', record.name);
    const allChecked = allUids.length === uids.length;
    const handleChange = async (checked, schema)=>{
        const parentUids = getParentUids(items, (data)=>data.uid === schema.uid);
        const childrenUids = getChildrenUids(null == schema ? void 0 : schema.children, []);
        if (checked) {
            const totalUids = childrenUids.concat(schema.uid);
            const newUids = uids.filter((v)=>!totalUids.includes(v));
            setUids([
                ...newUids
            ]);
            await resource.remove({
                values: totalUids
            });
        } else {
            const totalUids = childrenUids.concat(parentUids);
            setUids((prev)=>uniq([
                    ...prev,
                    ...totalUids
                ]));
            await resource.add({
                values: totalUids
            });
        }
        message.success(t('Saved successfully'));
    };
    const translateTitle = (menus)=>menus.map((menu)=>{
            const title = t(menu.title);
            if (menu.children) return {
                ...menu,
                title,
                children: translateTitle(menu.children)
            };
            return {
                ...menu,
                title
            };
        });
    return /*#__PURE__*/ jsx(Table, {
        className: styles,
        loading: loading,
        rowKey: 'uid',
        pagination: false,
        expandable: {
            defaultExpandAllRows: true
        },
        columns: [
            {
                dataIndex: 'title',
                title: t('Menu item title')
            },
            {
                dataIndex: 'accessible',
                title: /*#__PURE__*/ jsxs(Fragment, {
                    children: [
                        /*#__PURE__*/ jsx(Checkbox, {
                            checked: allChecked,
                            onChange: async (value)=>{
                                if (allChecked) await resource.set({
                                    values: []
                                });
                                else await resource.set({
                                    values: allUids
                                });
                                refresh();
                                message.success(t('Saved successfully'));
                            }
                        }),
                        ' ',
                        t('Accessible')
                    ]
                }),
                render: (_, schema)=>{
                    const checked = uids.includes(schema.uid);
                    return /*#__PURE__*/ jsx(Checkbox, {
                        checked: checked,
                        onChange: ()=>handleChange(checked, schema)
                    });
                }
            }
        ],
        dataSource: translateTitle(items)
    });
};
export { MenuConfigure };
