'use client';
import React, { Fragment, useCallback, useEffect, useState } from 'react';
import { Collapsible } from '../../../elements/Collapsible/index.js';
import { ErrorPill } from '../../../elements/ErrorPill/index.js';
import { useDocumentInfo } from '../../../providers/DocumentInfo/index.js';
import { usePreferences } from '../../../providers/Preferences/index.js';
import { useTranslation } from '../../../providers/Translation/index.js';
import { useFieldPath } from '../../FieldPathProvider/index.js';
import LabelComp from '../../Label/index.js';
import RenderFields from '../../RenderFields/index.js';
import { WatchChildErrors } from '../../WatchChildErrors/index.js';
import { withCondition } from '../../withCondition/index.js';
import { fieldBaseClass } from '../shared.js';
const baseClass = 'collapsible-field';
const CollapsibleField = (props)=>{
    const { Description, Error, Label: LabelFromProps, className, fieldMap, label, path: pathFromProps, permissions, readOnly, required } = props;
    const Label = LabelFromProps || /*#__PURE__*/ React.createElement(LabelComp, {
        label: label,
        required: required
    });
    const { path: pathFromContext } = useFieldPath();
    const path = pathFromProps || pathFromContext;
    const { i18n } = useTranslation();
    const initCollapsed = 'initCollapsed' in props ? props.initCollapsed : false;
    const { getPreference, setPreference } = usePreferences();
    const { preferencesKey } = useDocumentInfo();
    const [collapsedOnMount, setCollapsedOnMount] = useState();
    const fieldPreferencesKey = `collapsible-${path.replace(/\./g, '__')}`;
    const [errorCount, setErrorCount] = useState(0);
    const fieldHasErrors = errorCount > 0;
    const onToggle = useCallback(async (newCollapsedState)=>{
        const existingPreferences = await getPreference(preferencesKey);
        setPreference(preferencesKey, {
            ...existingPreferences,
            ...path ? {
                fields: {
                    ...existingPreferences?.fields || {},
                    [path]: {
                        ...existingPreferences?.fields?.[path],
                        collapsed: newCollapsedState
                    }
                }
            } : {
                fields: {
                    ...existingPreferences?.fields || {},
                    [fieldPreferencesKey]: {
                        ...existingPreferences?.fields?.[fieldPreferencesKey],
                        collapsed: newCollapsedState
                    }
                }
            }
        });
    }, [
        preferencesKey,
        fieldPreferencesKey,
        getPreference,
        setPreference,
        path
    ]);
    useEffect(()=>{
        const fetchInitialState = async ()=>{
            const preferences = await getPreference(preferencesKey);
            if (preferences) {
                const initCollapsedFromPref = path ? preferences?.fields?.[path]?.collapsed : preferences?.fields?.[fieldPreferencesKey]?.collapsed;
                setCollapsedOnMount(Boolean(initCollapsedFromPref));
            } else {
                setCollapsedOnMount(typeof initCollapsed === 'boolean' ? initCollapsed : false);
            }
        };
        fetchInitialState();
    }, [
        getPreference,
        preferencesKey,
        fieldPreferencesKey,
        initCollapsed,
        path
    ]);
    if (typeof collapsedOnMount !== 'boolean') return null;
    return /*#__PURE__*/ React.createElement(Fragment, null, /*#__PURE__*/ React.createElement(WatchChildErrors, {
        fieldMap: fieldMap,
        path: path,
        setErrorCount: setErrorCount
    }), /*#__PURE__*/ React.createElement("div", {
        className: [
            fieldBaseClass,
            baseClass,
            className,
            fieldHasErrors ? `${baseClass}--has-error` : `${baseClass}--has-no-error`
        ].filter(Boolean).join(' '),
        id: `field-${fieldPreferencesKey}${path ? `-${path.replace(/\./g, '__')}` : ''}`
    }, /*#__PURE__*/ React.createElement(Collapsible, {
        className: `${baseClass}__collapsible`,
        collapsibleStyle: fieldHasErrors ? 'error' : 'default',
        header: /*#__PURE__*/ React.createElement("div", {
            className: `${baseClass}__row-label-wrap`
        }, Label, fieldHasErrors && /*#__PURE__*/ React.createElement(ErrorPill, {
            count: errorCount,
            i18n: i18n,
            withMessage: true
        })),
        initCollapsed: collapsedOnMount,
        onToggle: onToggle
    }, /*#__PURE__*/ React.createElement(RenderFields, {
        fieldMap: fieldMap,
        forceRender: true,
        // indexPath={path}
        margins: "small"
    })), Description));
};
export default withCondition(CollapsibleField);

//# sourceMappingURL=index.js.map