import { jsx, jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useFieldSchema } from "@tachybase/schema";
import { error, forEach } from "@tachybase/utils/client";
import { Select, Space } from "antd";
import lodash from "lodash";
import { useTranslation } from "react-i18next";
import { useToken } from "../__builtins__/index.mjs";
import { useAPIClient } from "../../../api-client/index.mjs";
import { findFormBlock } from "../../../block-provider/index.mjs";
import { useFormBlockContext } from "../../../block-provider/FormBlockProvider.mjs";
import { useCollectionManager_deprecated } from "../../../collection-manager/index.mjs";
import { compatibleDataId } from "../../../schema-settings/DataTemplates/FormDataTemplates.mjs";
import { RemoteSelect } from "../remote-select/index.mjs";
const useDataTemplates = ()=>{
    const fieldSchema = useFieldSchema();
    const { t } = useTranslation();
    const { duplicateData } = useFormBlockContext();
    const { getCollectionJoinField } = useCollectionManager_deprecated();
    if (duplicateData) return duplicateData;
    const { items = [], display = true } = findDataTemplates(fieldSchema);
    items.forEach((item)=>{
        try {
            var _item_fields;
            item.fields = null == (_item_fields = item.fields) ? void 0 : _item_fields.map((field)=>{
                const joinField = getCollectionJoinField("".concat(item.collection, ".").concat(field));
                if (joinField) return field;
                return '';
            }).filter(Boolean);
        } catch (err) {
            error(err);
            item.fields = [];
        }
    });
    const templates = [
        {
            key: 'none',
            title: t('None')
        }
    ].concat(items.map((t, i)=>({
            key: i,
            ...t,
            isLeaf: null !== t.dataId && void 0 !== t.dataId,
            titleCollectionField: (null == t ? void 0 : t.titleField) && getCollectionJoinField("".concat(t.collection, ".").concat(t.titleField))
        })));
    const defaultTemplate = items.find((item)=>item.default);
    return {
        templates,
        display,
        defaultTemplate,
        enabled: items.length > 0 && items.every((item)=>item.dataId || item.dataScope)
    };
};
const Templates = (param)=>{
    let { style = {}, form } = param;
    const { token } = useToken();
    const { templates, display, enabled, defaultTemplate } = useDataTemplates();
    const { getCollectionJoinField } = useCollectionManager_deprecated();
    const templateOptions = compatibleDataId(templates);
    const [targetTemplate, setTargetTemplate] = useState((null == defaultTemplate ? void 0 : defaultTemplate.key) || 'none');
    const [targetTemplateData, setTemplateData] = useState(null);
    const api = useAPIClient();
    const { t } = useTranslation();
    useEffect(()=>{
        if (enabled && defaultTemplate) {
            form.__template = true;
            if ('duplicate' === defaultTemplate.key) handleTemplateDataChange(defaultTemplate.dataId, defaultTemplate);
        }
    }, []);
    useEffect(()=>{
        if (!(null == templateOptions ? void 0 : templateOptions.some((v)=>v.key === targetTemplate))) handleTemplateChange('none');
    }, [
        templateOptions
    ]);
    const wrapperStyle = useMemo(()=>({
            display: 'flex',
            alignItems: 'center',
            backgroundColor: token.colorFillAlter,
            padding: '1em',
            ...style
        }), [
        style,
        token.colorFillAlter
    ]);
    const labelStyle = useMemo(()=>({
            fontSize: token.fontSize,
            fontWeight: 'bold',
            whiteSpace: 'nowrap',
            marginRight: token.marginXS
        }), [
        token.fontSize,
        token.marginXS
    ]);
    const handleTemplateChange = useCallback(async (value)=>{
        setTargetTemplate(value);
        setTemplateData(null);
        null == form || form.reset();
    }, []);
    const handleTemplateDataChange = useCallback(async (value, option)=>{
        const template = {
            ...option,
            dataId: value
        };
        setTemplateData(option);
        fetchTemplateData(api, template, t).then((data)=>{
            if (form && data) {
                form.reset();
                form.__template = true;
                forEach(data, (value, key)=>{
                    if (value) {
                        var _form_setInitialValuesIn;
                        form.values[key] = value;
                        null == form || null == (_form_setInitialValuesIn = form.setInitialValuesIn) || _form_setInitialValuesIn.call(form, key, value);
                    }
                });
            }
            return data;
        }).catch((err)=>{
            console.error(err);
        });
    }, []);
    if (!enabled || !display) return null;
    const template = null == templateOptions ? void 0 : templateOptions.find((v)=>v.key === targetTemplate);
    return /*#__PURE__*/ jsx("div", {
        style: wrapperStyle,
        children: /*#__PURE__*/ jsxs(Space, {
            wrap: true,
            children: [
                /*#__PURE__*/ jsxs("label", {
                    style: labelStyle,
                    children: [
                        t('Data template'),
                        ": "
                    ]
                }),
                /*#__PURE__*/ jsx(Select, {
                    "data-testid": "select-form-data-template",
                    popupMatchSelectWidth: false,
                    options: templateOptions,
                    fieldNames: {
                        label: 'title',
                        value: 'key'
                    },
                    value: targetTemplate,
                    onChange: handleTemplateChange
                }),
                'none' !== targetTemplate && template && /*#__PURE__*/ jsx(RemoteSelect, {
                    style: {
                        width: 220
                    },
                    fieldNames: {
                        label: null == template ? void 0 : template.titleField,
                        value: 'id'
                    },
                    target: null == template ? void 0 : template.collection,
                    value: targetTemplateData,
                    objectValue: true,
                    service: {
                        resource: null == template ? void 0 : template.collection,
                        params: {
                            filter: null == template ? void 0 : template.dataScope
                        }
                    },
                    onChange: (value)=>handleTemplateDataChange(null == value ? void 0 : value.id, {
                            ...value,
                            ...template
                        }),
                    targetField: getCollectionJoinField("".concat(null == template ? void 0 : template.collection, ".").concat(template.titleField))
                })
            ]
        })
    });
};
function findDataTemplates(fieldSchema) {
    const formSchema = findFormBlock(fieldSchema);
    if (formSchema) return lodash.cloneDeep(formSchema['x-data-templates']) || {};
    return {};
}
async function fetchTemplateData(api, template, t) {
    if (0 === template.fields.length || !template.dataId) return;
    return api.resource(template.collection).get({
        filterByTk: template.dataId,
        fields: template.fields,
        isTemplate: true
    }).then((data)=>{
        var _data_data;
        return null == (_data_data = data.data) ? void 0 : _data_data.data;
    });
}
export { Templates, fetchTemplateData };
