'use client';
import { jsxDEV as _jsxDEV } from "react/jsx-dev-runtime";
import React, { useCallback, useEffect } from 'react';
import { Form, useForm } from '../../../forms/Form/index.js';
import { WatchChildErrors } from '../../../forms/WatchChildErrors/index.js';
import { useConfig } from '../../../providers/Config/index.js';
import { useDocumentEvents } from '../../../providers/DocumentEvents/index.js';
import { useDocumentInfo } from '../../../providers/DocumentInfo/index.js';
import { OperationProvider } from '../../../providers/Operation/index.js';
import { useServerFunctions } from '../../../providers/ServerFunctions/index.js';
import { abortAndIgnore, handleAbortRef } from '../../../utilities/abortAndIgnore.js';
import { useDocumentDrawerContext } from '../../DocumentDrawer/Provider.js';
import { DocumentFields } from '../../DocumentFields/index.js';
import { MoveDocToFolder } from '../../FolderView/MoveDocToFolder/index.js';
import { Upload_v4 } from '../../Upload/index.js';
import { useFormsManager } from '../FormsManager/index.js';
import './index.scss';
const baseClass = 'collection-edit';
// This component receives props only on _pages_
// When rendered within a drawer, props are empty
// This is solely to support custom edit views which get server-rendered
export function EditForm({ resetUploadEdits, submitted, updateUploadEdits, uploadEdits }) {
    const { action, collectionSlug: docSlug, docPermissions, getDocPreferences, hasSavePermission, initialState, isInitializing, Upload: CustomUpload } = useDocumentInfo();
    const { drawerSlug, onSave: onSaveFromContext } = useDocumentDrawerContext();
    const { getFormState } = useServerFunctions();
    const { config: { folders }, getEntityConfig } = useConfig();
    const abortOnChangeRef = React.useRef(null);
    const collectionConfig = getEntityConfig({
        collectionSlug: docSlug
    });
    const { reportUpdate } = useDocumentEvents();
    const collectionSlug = collectionConfig.slug;
    const [schemaPath] = React.useState(collectionSlug);
    const onSave = useCallback((json)=>{
        reportUpdate({
            doc: json?.doc || json?.result,
            drawerSlug,
            entitySlug: collectionSlug,
            operation: 'create',
            updatedAt: json?.result?.updatedAt || new Date().toISOString()
        });
        if (typeof onSaveFromContext === 'function') {
            void onSaveFromContext({
                ...json,
                operation: 'create'
            });
        }
        resetUploadEdits();
    }, [
        collectionSlug,
        onSaveFromContext,
        reportUpdate,
        resetUploadEdits,
        drawerSlug
    ]);
    const onChange = useCallback(async ({ formState: prevFormState, submitted })=>{
        const controller = handleAbortRef(abortOnChangeRef);
        const docPreferences = await getDocPreferences();
        const { state: newFormState } = await getFormState({
            collectionSlug,
            docPermissions,
            docPreferences,
            formState: prevFormState,
            operation: 'create',
            schemaPath,
            signal: controller.signal,
            skipValidation: !submitted
        });
        abortOnChangeRef.current = null;
        return newFormState;
    }, [
        collectionSlug,
        schemaPath,
        getDocPreferences,
        getFormState,
        docPermissions
    ]);
    useEffect(()=>{
        const abortOnChange = abortOnChangeRef.current;
        return ()=>{
            abortAndIgnore(abortOnChange);
        };
    }, []);
    return /*#__PURE__*/ _jsxDEV(OperationProvider, {
        operation: "create",
        children: /*#__PURE__*/ _jsxDEV(Form, {
            action: action,
            className: `${baseClass}__form`,
            disabled: isInitializing || !hasSavePermission,
            initialState: isInitializing ? undefined : initialState,
            isInitializing: isInitializing,
            method: "POST",
            onChange: [
                onChange
            ],
            onSuccess: onSave,
            submitted: submitted,
            children: [
                /*#__PURE__*/ _jsxDEV(DocumentFields, {
                    BeforeFields: /*#__PURE__*/ _jsxDEV(React.Fragment, {
                        children: CustomUpload || /*#__PURE__*/ _jsxDEV(Upload_v4, {
                            collectionSlug: collectionConfig.slug,
                            customActions: [
                                folders && collectionConfig.folders && /*#__PURE__*/ _jsxDEV(MoveDocToFolder, {
                                    buttonProps: {
                                        buttonStyle: 'pill',
                                        size: 'small'
                                    },
                                    folderCollectionSlug: folders.slug,
                                    folderFieldName: folders.fieldName
                                }, "move-doc-to-folder", false, {
                                    fileName: "src/elements/BulkUpload/EditForm/index.tsx",
                                    lineNumber: 138,
                                    columnNumber: 23
                                }, void 0)
                            ].filter(Boolean),
                            initialState: initialState,
                            resetUploadEdits: resetUploadEdits,
                            updateUploadEdits: updateUploadEdits,
                            uploadConfig: collectionConfig.upload,
                            uploadEdits: uploadEdits
                        }, void 0, false, {
                            fileName: "src/elements/BulkUpload/EditForm/index.tsx",
                            lineNumber: 134,
                            columnNumber: 17
                        }, void 0)
                    }, void 0, false, {
                        fileName: "src/elements/BulkUpload/EditForm/index.tsx",
                        lineNumber: 132,
                        columnNumber: 13
                    }, void 0),
                    docPermissions: docPermissions,
                    fields: collectionConfig.fields,
                    schemaPathSegments: [
                        collectionConfig.slug
                    ]
                }, void 0, false, {
                    fileName: "src/elements/BulkUpload/EditForm/index.tsx",
                    lineNumber: 130,
                    columnNumber: 9
                }, this),
                /*#__PURE__*/ _jsxDEV(ReportAllErrors, {}, void 0, false, {
                    fileName: "src/elements/BulkUpload/EditForm/index.tsx",
                    lineNumber: 162,
                    columnNumber: 9
                }, this),
                /*#__PURE__*/ _jsxDEV(GetFieldProxy, {}, void 0, false, {
                    fileName: "src/elements/BulkUpload/EditForm/index.tsx",
                    lineNumber: 163,
                    columnNumber: 9
                }, this)
            ]
        }, void 0, true, {
            fileName: "src/elements/BulkUpload/EditForm/index.tsx",
            lineNumber: 119,
            columnNumber: 7
        }, this)
    }, void 0, false, {
        fileName: "src/elements/BulkUpload/EditForm/index.tsx",
        lineNumber: 118,
        columnNumber: 5
    }, this);
}
function GetFieldProxy() {
    const { getFields } = useForm();
    const { getFormDataRef } = useFormsManager();
    useEffect(()=>{
        // eslint-disable-next-line react-compiler/react-compiler -- TODO: fix
        getFormDataRef.current = getFields;
    }, [
        getFields,
        getFormDataRef
    ]);
    return null;
}
function ReportAllErrors() {
    const { docConfig } = useDocumentInfo();
    const { activeIndex, setFormTotalErrorCount } = useFormsManager();
    const errorCountRef = React.useRef(0);
    const reportFormErrorCount = React.useCallback((errorCount)=>{
        if (errorCount === errorCountRef.current) {
            return;
        }
        setFormTotalErrorCount({
            errorCount,
            index: activeIndex
        });
        errorCountRef.current = errorCount;
    }, [
        activeIndex,
        setFormTotalErrorCount
    ]);
    if (!docConfig) {
        return null;
    }
    return /*#__PURE__*/ _jsxDEV(WatchChildErrors, {
        fields: docConfig.fields,
        path: [],
        setErrorCount: reportFormErrorCount
    }, void 0, false, {
        fileName: "src/elements/BulkUpload/EditForm/index.tsx",
        lineNumber: 202,
        columnNumber: 5
    }, this);
}

//# sourceMappingURL=index.js.map