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, useActionContext } from "../action/index.mjs";
import { EllipsisWithTooltip } from "../input/EllipsisWithTooltip.mjs";
import { useAssociationFieldContext, useCustomTitle, useFieldNames, useInsertSchema } from "./hooks.mjs";
import { transformNestedData } from "./InternalCascadeSelect.mjs";
import schema 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 } = useCustomTitle(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.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: 'drawer',
                            snapshot: (null == collectionField ? void 0 : collectionField.interface) === 'snapshot',
                            fieldSchema: fieldSchema
                        },
                        children: renderRecordProvider()
                    })
                ]
            })
        })
    });
}, {
    displayName: 'ReadPrettyInternalViewer'
});
export { ReadPrettyInternalViewer, isObject };
