import { jsx, jsxs } from "react/jsx-runtime";
import { Fragment, useRef, useState } from "react";
import { RecursionField, observer, toArr, useField, useFieldSchema } from "@tachybase/schema";
import { useTranslation } from "react-i18next";
import { useDesignable } from "../../index.mjs";
import { BlockAssociationContext, WithoutTableFieldResource } from "../../../block-provider/index.mjs";
import { CollectionProvider_deprecated, useCollectionManager_deprecated } from "../../../collection-manager/index.mjs";
import { DeclareVariable } from "../../../modules/variable/DeclareVariable.mjs";
import { RecordProvider, useRecord } from "../../../record-provider/index.mjs";
import { FormProvider } from "../../core/index.mjs";
import { useCompile } from "../../hooks/index.mjs";
import { ActionContextProvider, OpenMode, useActionContext } from "../action/index.mjs";
import { EllipsisWithTooltip } from "../input/EllipsisWithTooltip.mjs";
import { useAssociationFieldContext, useFieldNames, useInsertSchema } from "./hooks.mjs";
import { transformNestedData } from "./InternalCascadeSelect.mjs";
import schema_0 from "./schema.mjs";
import { getLabelFormatValue, useLabelUiSchemaV2 } from "./util.mjs";
const toValue = (value, placeholder)=>{
    if (null == value) return placeholder;
    return value;
};
function isObject(value) {
    return 'object' == typeof value && null !== value;
}
const ReadPrettyInternalViewer = observer((props)=>{
    const { t } = useTranslation();
    const fieldSchema = useFieldSchema();
    const recordCtx = useRecord();
    const { getCollection } = useCollectionManager_deprecated();
    const { enableLink } = fieldSchema['x-component-props'] || {};
    const field = useField();
    const defFieldNames = useFieldNames(props);
    const [visible, setVisible] = useState(false);
    const insertViewer = useInsertSchema('Viewer');
    const { options: collectionField } = useAssociationFieldContext();
    const [record, setRecord] = useState({});
    const compile = useCompile();
    const { designable } = useDesignable();
    const { snapshot } = useActionContext();
    const targetCollection = getCollection(null == collectionField ? void 0 : collectionField.target);
    const isTreeCollection = (null == targetCollection ? void 0 : targetCollection.template) === 'tree';
    const ellipsisWithTooltipRef = useRef();
    const getLabelUiSchema = useLabelUiSchemaV2();
    const { formulaRecord, fieldNames } = customTitle(recordCtx, fieldSchema, defFieldNames);
    const renderRecords = ()=>toArr(formulaRecord[fieldSchema['name']] || props.value).map((record, index, arr)=>{
            var _getCollection_options, _getCollection, _targetCollection_fieldsMap_, _targetCollection_fieldsMap, _getCollection_options1, _getCollection1, _targetCollection_fieldsMap_1, _targetCollection_fieldsMap1;
            const value = null == record ? void 0 : record[(null == fieldNames ? void 0 : fieldNames.label) || 'label'];
            const label = isTreeCollection ? transformNestedData(record).map((o)=>null == o ? void 0 : o[(null == fieldNames ? void 0 : fieldNames.label) || 'label']).join(' / ') : isObject(value) ? (null == (_getCollection = getCollection(null == targetCollection ? void 0 : null == (_targetCollection_fieldsMap = targetCollection.fieldsMap) ? void 0 : null == (_targetCollection_fieldsMap_ = _targetCollection_fieldsMap[(null == fieldNames ? void 0 : fieldNames.label) || 'label']) ? void 0 : _targetCollection_fieldsMap_.target)) ? void 0 : null == (_getCollection_options = _getCollection.options) ? void 0 : _getCollection_options.titleField) ? value[null == (_getCollection1 = getCollection(null == targetCollection ? void 0 : null == (_targetCollection_fieldsMap1 = targetCollection.fieldsMap) ? void 0 : null == (_targetCollection_fieldsMap_1 = _targetCollection_fieldsMap1[(null == fieldNames ? void 0 : fieldNames.label) || 'label']) ? void 0 : _targetCollection_fieldsMap_1.target)) ? void 0 : null == (_getCollection_options1 = _getCollection1.options) ? void 0 : _getCollection_options1.titleField] : JSON.stringify(value) : value;
            const val = toValue(compile(label), 'N/A');
            const labelUiSchema = getLabelUiSchema((null == record ? void 0 : record.__collection) || (null == collectionField ? void 0 : collectionField.target), (null == fieldNames ? void 0 : fieldNames.label) || 'label');
            const text = getLabelFormatValue(compile(labelUiSchema), val, true);
            return /*#__PURE__*/ jsxs(Fragment, {
                children: [
                    /*#__PURE__*/ jsx("span", {
                        children: snapshot ? text : false !== enableLink ? /*#__PURE__*/ jsx("a", {
                            onClick: (e)=>{
                                var _ellipsisWithTooltipRef_current;
                                e.stopPropagation();
                                e.preventDefault();
                                if (designable) insertViewer(schema_0.Viewer);
                                setVisible(true);
                                setRecord(record);
                                null == ellipsisWithTooltipRef || null == (_ellipsisWithTooltipRef_current = ellipsisWithTooltipRef.current) || _ellipsisWithTooltipRef_current.setPopoverVisible(false);
                            },
                            children: text
                        }) : text
                    }),
                    index < arr.length - 1 ? /*#__PURE__*/ jsx("span", {
                        style: {
                            marginRight: 4,
                            color: '#aaa'
                        },
                        children: ","
                    }) : null
                ]
            }, "".concat(null == record ? void 0 : record.id, "_").concat(index));
        });
    const renderWithoutTableFieldResourceProvider = ()=>/*#__PURE__*/ jsx(DeclareVariable, {
            name: "$nPopupRecord",
            title: t('Current popup record'),
            value: record,
            collection: targetCollection,
            children: /*#__PURE__*/ jsx(WithoutTableFieldResource.Provider, {
                value: true,
                children: /*#__PURE__*/ jsx(FormProvider, {
                    children: /*#__PURE__*/ jsx(RecursionField, {
                        schema: fieldSchema,
                        onlyRenderProperties: true,
                        basePath: field.address,
                        filterProperties: (s)=>'AssociationField.Viewer' === s['x-component']
                    })
                })
            })
        });
    const renderRecordProvider = ()=>{
        var _fieldSchema_xcollectionfield;
        const collectionFieldNames = null == fieldSchema ? void 0 : null == (_fieldSchema_xcollectionfield = fieldSchema['x-collection-field']) ? void 0 : _fieldSchema_xcollectionfield.split('.');
        return collectionFieldNames && collectionFieldNames.length > 2 ? /*#__PURE__*/ jsx(RecordProvider, {
            record: record,
            parent: formulaRecord[collectionFieldNames[1]],
            children: renderWithoutTableFieldResourceProvider()
        }) : /*#__PURE__*/ jsx(RecordProvider, {
            record: record,
            parent: formulaRecord,
            children: renderWithoutTableFieldResourceProvider()
        });
    };
    var _collectionField_target;
    return /*#__PURE__*/ jsx("div", {
        children: /*#__PURE__*/ jsx(BlockAssociationContext.Provider, {
            value: "".concat(null == collectionField ? void 0 : collectionField.collectionName, ".").concat(null == collectionField ? void 0 : collectionField.name),
            children: /*#__PURE__*/ jsxs(CollectionProvider_deprecated, {
                name: null != (_collectionField_target = null == collectionField ? void 0 : collectionField.target) ? _collectionField_target : null == collectionField ? void 0 : collectionField.targetCollection,
                children: [
                    /*#__PURE__*/ jsx(EllipsisWithTooltip, {
                        ellipsis: true,
                        ref: ellipsisWithTooltipRef,
                        children: renderRecords()
                    }),
                    /*#__PURE__*/ jsx(ActionContextProvider, {
                        value: {
                            visible,
                            setVisible,
                            openMode: OpenMode.DEFAULT,
                            snapshot: (null == collectionField ? void 0 : collectionField.interface) === 'snapshot',
                            fieldSchema: fieldSchema
                        },
                        children: renderRecordProvider()
                    })
                ]
            })
        })
    });
}, {
    displayName: 'ReadPrettyInternalViewer'
});
const customTitle = (record, schema, fieldNames)=>{
    var _schema_xcomponentprops, _schema_xcomponentprops_fieldNames, _schema_xcomponentprops1;
    if ((null == (_schema_xcomponentprops = schema['x-component-props']) ? void 0 : _schema_xcomponentprops.mode) === 'CustomTitle' && (null == (_schema_xcomponentprops1 = schema['x-component-props']) ? void 0 : null == (_schema_xcomponentprops_fieldNames = _schema_xcomponentprops1.fieldNames) ? void 0 : _schema_xcomponentprops_fieldNames.formula)) {
        var _schema_xcomponentprops_fieldNames1, _schema_xcomponentprops2;
        const regex = /{{(.*?)}}/g;
        const valueOject = {};
        let outputStr = '';
        let match;
        const formula = null == (_schema_xcomponentprops2 = schema['x-component-props']) ? void 0 : null == (_schema_xcomponentprops_fieldNames1 = _schema_xcomponentprops2.fieldNames) ? void 0 : _schema_xcomponentprops_fieldNames1.formula;
        while(match = regex.exec(formula))if (match[1].includes('.')) {
            const fieldList = [
                schema.name
            ];
            fieldList.push(...match[1].split('.'));
            const result = {
                currRecord: record,
                value: ''
            };
            fieldList.forEach((value, index)=>{
                var _result_currRecord;
                if (fieldList.length - 1 !== index) {
                    var _result_currRecord1;
                    result.currRecord = null == (_result_currRecord1 = result.currRecord) ? void 0 : _result_currRecord1[value];
                    return;
                }
                result.value = null == (_result_currRecord = result.currRecord) ? void 0 : _result_currRecord[value];
            });
            var _result_value;
            valueOject[match[1]] = null != (_result_value = result.value) ? _result_value : '';
        } else {
            var _record_schema_name;
            valueOject[match[1]] = (null == (_record_schema_name = record[schema['name']]) ? void 0 : _record_schema_name[match[1]]) || '';
        }
        outputStr = replacePlaceholders(formula, valueOject);
        record[schema['name']] = {
            ...record[schema['name']],
            customLabel: outputStr
        };
        return {
            formulaRecord: record,
            fieldNames: {
                ...fieldNames,
                label: 'customLabel'
            }
        };
    }
    return {
        formulaRecord: record,
        fieldNames
    };
};
const replacePlaceholders = (inputStr, values)=>inputStr.replace(/{{(.*?)}}/g, function(match, placeholder) {
        return Object.prototype.hasOwnProperty.call(values, placeholder) ? values[placeholder] : match;
    });
export { ReadPrettyInternalViewer, isObject };
