import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useMemo, useState } from "react";
import { fuzzysearch } from "@tego/client";
import { useDebounce } from "ahooks";
import { Button, Card, Form, Input, Radio, Result, Select, Space, Spin, Table, Tag, Typography } from "antd";
import lodash from "lodash";
import { useTranslation as external_react_i18next_useTranslation } from "react-i18next";
import { useRequest } from "../../api-client/index.mjs";
import { i18n } from "../../i18n/index.mjs";
import "../../style/index.mjs";
import { useACLRoleContext } from "../acl/index.mjs";
import { SwitchAction } from "./PluginCard.mjs";
import { PluginDetail } from "./PluginDetail.mjs";
import { useStyles } from "./style.mjs";
const ViewAction = (param)=>{
    let { record } = param;
    const [plugin, setPlugin] = useState(void 0);
    return /*#__PURE__*/ jsxs(Fragment, {
        children: [
            plugin && /*#__PURE__*/ jsx(PluginDetail, {
                plugin: plugin,
                onCancel: ()=>setPlugin(void 0)
            }),
            /*#__PURE__*/ jsx(Button, {
                type: "link",
                onClick: ()=>{
                    setPlugin(record);
                },
                children: i18n.t('View')
            })
        ]
    });
};
const PluginDescription = (param)=>{
    let { description, record } = param;
    const { theme } = useStyles();
    return /*#__PURE__*/ jsx(Typography.Paragraph, {
        type: record.isCompatible ? 'secondary' : 'danger',
        children: record.isCompatible ? description : i18n.t('Plugin dependencies check failed')
    });
};
const LocalPlugins = ()=>{
    const { t } = external_react_i18next_useTranslation();
    const { theme } = useStyles();
    const { data, loading, refresh } = useRequest({
        url: 'pm:list'
    });
    const [searchValue, setSearchValue] = useState('');
    const [enabled, setEnabled] = useState('all');
    const [keywords, setKeywords] = useState([]);
    const columns = useMemo(()=>[
            {
                title: t('Name'),
                dataIndex: 'name',
                key: 'name',
                render: (_, param)=>{
                    let { displayName, name, packageName } = param;
                    return /*#__PURE__*/ jsx("span", {
                        children: displayName || name || packageName
                    });
                }
            },
            {
                title: t('Keywords'),
                dataIndex: 'keywords',
                key: 'keywords',
                render: (keywords)=>null == keywords ? void 0 : keywords.map((keyword)=>/*#__PURE__*/ jsx(Tag, {
                            children: t(keyword)
                        }, keyword))
            },
            {
                title: t("Description"),
                dataIndex: "description",
                key: "description",
                render: (description, record)=>/*#__PURE__*/ jsx(PluginDescription, {
                        description: description,
                        record: record
                    })
            },
            {
                title: t('Action'),
                key: 'action',
                render: (_, record)=>/*#__PURE__*/ jsxs(Space, {
                        size: "middle",
                        children: [
                            /*#__PURE__*/ jsx(ViewAction, {
                                record: record
                            }),
                            /*#__PURE__*/ jsx(SwitchAction, {
                                ...record
                            })
                        ]
                    })
            }
        ], []);
    const filteredList = ((null == data ? void 0 : data.data) || []).filter((data)=>{
        var _data_description;
        return fuzzysearch(searchValue, data.name) || fuzzysearch(searchValue, data.packageName) || fuzzysearch(searchValue, null != (_data_description = data.description) ? _data_description : '') || fuzzysearch(searchValue, data.displayName);
    }).filter((data)=>'all' === enabled || 'enabled' === enabled && data.enabled || 'disabled' === enabled && !data.enabled).filter((data)=>0 === keywords.length || keywords.some((keyword)=>{
            var _data_keywords;
            return null == (_data_keywords = data.keywords) ? void 0 : _data_keywords.includes(keyword);
        }));
    const filterList = useMemo(()=>{
        let list = (null == data ? void 0 : data.data) || [];
        list = list.reverse();
        return [
            {
                type: 'All',
                list: list
            },
            {
                type: 'Built-in',
                list: lodash.filter(list, (item)=>item.builtIn)
            },
            {
                type: 'Enabled',
                list: lodash.filter(list, (item)=>item.enabled)
            },
            {
                type: 'Not enabled',
                list: lodash.filter(list, (item)=>!item.enabled)
            },
            {
                type: 'Problematic',
                list: lodash.filter(list, (item)=>!item.isCompatible)
            }
        ];
    }, [
        null == data ? void 0 : data.data
    ]);
    const [filterIndex, setFilterIndex] = useState(0);
    const [keyword, setKeyword] = useState(null);
    const debouncedSearchValue = useDebounce(searchValue, {
        wait: 100
    });
    const keyWordlists = [
        'Data model tools',
        'Data sources',
        'Collections',
        'Collection fields',
        'Blocks',
        'Actions',
        'Workflow',
        'Users & permissions',
        'Authentication',
        'System management',
        'Logging and monitoring',
        'Others'
    ];
    const keyWordsfilterList = useMemo(()=>{
        const list = keyWordlists.map((i)=>{
            if ('Others' === i) {
                const result = null == data ? void 0 : data.data.filter((v)=>!v.keywords || !v.keywords.every((k)=>keyWordlists.includes(k)));
                return {
                    key: i,
                    list: result
                };
            }
            const result = null == data ? void 0 : data.data.filter((v)=>{
                var _v_keywords;
                return null == (_v_keywords = v.keywords) ? void 0 : _v_keywords.includes(i);
            });
            return {
                key: i,
                list: result
            };
        });
        return list;
    }, [
        keyWordlists
    ]);
    useMemo(()=>{
        var _filterList_filterIndex;
        let list = (null == (_filterList_filterIndex = filterList[filterIndex]) ? void 0 : _filterList_filterIndex.list) || [];
        if (!filterIndex && keyword) list = keyWordsfilterList.find((v)=>v.key === keyword).list;
        else if (filterIndex && keyword) {
            const keyList = keyWordsfilterList.find((v)=>v.key === keyword).list;
            list = keyList.filter((value)=>list.find((k)=>k.name === value.name));
        }
        const searchLowerCaseValue = debouncedSearchValue.toLocaleLowerCase().trim();
        if (searchLowerCaseValue) list = lodash.filter(list, (item)=>String(item.displayName || '').toLocaleLowerCase().includes(searchLowerCaseValue) || String(item.description || '').toLocaleLowerCase().includes(searchLowerCaseValue));
        return list.sort((a, b)=>a.displayName.localeCompare(b.displayName));
    }, [
        filterIndex,
        filterList,
        debouncedSearchValue,
        keyword
    ]);
    if (loading) return /*#__PURE__*/ jsx(Spin, {});
    return /*#__PURE__*/ jsx(Fragment, {
        children: /*#__PURE__*/ jsxs(Card, {
            style: {
                marginTop: '8px'
            },
            children: [
                /*#__PURE__*/ jsxs(Form, {
                    style: {
                        marginBottom: '8px'
                    },
                    layout: "inline",
                    children: [
                        /*#__PURE__*/ jsx(Form.Item, {
                            label: t('Status'),
                            children: /*#__PURE__*/ jsx(Radio.Group, {
                                options: [
                                    {
                                        label: t('all'),
                                        value: 'all'
                                    },
                                    {
                                        label: t('enabled'),
                                        value: 'enabled'
                                    },
                                    {
                                        label: t('disabled'),
                                        value: 'disabled'
                                    }
                                ],
                                onChange: (e)=>setEnabled(e.target.value),
                                value: enabled,
                                optionType: "button"
                            })
                        }),
                        /*#__PURE__*/ jsx(Form.Item, {
                            label: t('Keywords'),
                            children: /*#__PURE__*/ jsx(Select, {
                                mode: "multiple",
                                style: {
                                    minWidth: '20em'
                                },
                                allowClear: true,
                                value: keywords,
                                placeholder: t('Please select'),
                                onChange: setKeywords,
                                options: keyWordlists.map((keyword)=>({
                                        label: t(keyword),
                                        value: keyword
                                    }))
                            })
                        }),
                        /*#__PURE__*/ jsx(Form.Item, {
                            label: t('Search'),
                            children: /*#__PURE__*/ jsx(Input, {
                                value: searchValue,
                                placeholder: t("Name or descriptions"),
                                onChange: (e)=>setSearchValue(e.target.value)
                            })
                        })
                    ]
                }),
                /*#__PURE__*/ jsx(Table, {
                    columns: columns,
                    dataSource: filteredList,
                    rowKey: "id",
                    pagination: {
                        pageSize: 100
                    }
                })
            ]
        })
    });
};
const PluginManager = ()=>{
    const { snippets = [] } = useACLRoleContext();
    return snippets.includes('pm') ? /*#__PURE__*/ jsx(LocalPlugins, {}) : /*#__PURE__*/ jsx(Result, {
        status: "404",
        title: "404",
        subTitle: "Sorry, the page you visited does not exist."
    });
};
export { PluginManager };
