'use client';
import { jsxDEV as _jsxDEV } from "react/jsx-dev-runtime";
import { useModal } from '@faceless-ui/modal';
import { getTranslation } from '@payloadcms/translations';
import { useRouter, useSearchParams } from 'next/navigation.js';
import { combineWhereConstraints, formatAdminURL, mergeListSearchAndWhere, unflatten } from 'payload/shared';
import * as qs from 'qs-esm';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useForm } from '../../forms/Form/context.js';
import { Form } from '../../forms/Form/index.js';
import { RenderField } from '../../forms/RenderFields/RenderField.js';
import { FormSubmit } from '../../forms/Submit/index.js';
import { XIcon } from '../../icons/X/index.js';
import { useAuth } from '../../providers/Auth/index.js';
import { useConfig } from '../../providers/Config/index.js';
import { DocumentInfoProvider } from '../../providers/DocumentInfo/index.js';
import { useLocale } from '../../providers/Locale/index.js';
import { OperationContext } from '../../providers/Operation/index.js';
import { useServerFunctions } from '../../providers/ServerFunctions/index.js';
import { useTranslation } from '../../providers/Translation/index.js';
import { abortAndIgnore, handleAbortRef } from '../../utilities/abortAndIgnore.js';
import { parseSearchParams } from '../../utilities/parseSearchParams.js';
import { FieldSelect } from '../FieldSelect/index.js';
import './index.scss';
import '../../forms/RenderFields/index.scss';
import { baseClass } from './index.js';
const Submit = ({ action, disabled })=>{
    const { submit } = useForm();
    const { t } = useTranslation();
    const save = useCallback(()=>{
        void submit({
            action,
            method: 'PATCH',
            skipValidation: true
        });
    }, [
        action,
        submit
    ]);
    return /*#__PURE__*/ _jsxDEV(FormSubmit, {
        className: `${baseClass}__save`,
        disabled: disabled,
        onClick: save,
        children: t('general:save')
    }, void 0, false, {
        fileName: "src/elements/EditMany/DrawerContent.tsx",
        lineNumber: 56,
        columnNumber: 5
    }, this);
};
const PublishButton = ({ action, disabled })=>{
    const { submit } = useForm();
    const { t } = useTranslation();
    const save = useCallback(()=>{
        void submit({
            action,
            method: 'PATCH',
            overrides: {
                _status: 'published'
            },
            skipValidation: true
        });
    }, [
        action,
        submit
    ]);
    return /*#__PURE__*/ _jsxDEV(FormSubmit, {
        className: `${baseClass}__publish`,
        disabled: disabled,
        onClick: save,
        children: t('version:publishChanges')
    }, void 0, false, {
        fileName: "src/elements/EditMany/DrawerContent.tsx",
        lineNumber: 81,
        columnNumber: 5
    }, this);
};
const SaveDraftButton = ({ action, disabled })=>{
    const { submit } = useForm();
    const { t } = useTranslation();
    const save = useCallback(()=>{
        void submit({
            action,
            method: 'PATCH',
            overrides: {
                _status: 'draft'
            },
            skipValidation: true
        });
    }, [
        action,
        submit
    ]);
    return /*#__PURE__*/ _jsxDEV(FormSubmit, {
        buttonStyle: "secondary",
        className: `${baseClass}__draft`,
        disabled: disabled,
        onClick: save,
        children: t('version:saveDraft')
    }, void 0, false, {
        fileName: "src/elements/EditMany/DrawerContent.tsx",
        lineNumber: 106,
        columnNumber: 5
    }, this);
};
/**
   * The total count of selected items
   */ /**
   * The slug of the drawer
   */ /**
   * The IDs of the selected items
   */ /**
   * The function to call after a successful action
   */ /**
   * Whether all items are selected
   */ /**
   * The fields that are selected to bulk edit
   */ /**
   * The function to set the selected fields to bulk edit
   */ export const EditManyDrawerContent = (props)=>{
    const { collection, collection: { fields, labels: { plural, singular } } = {}, count, drawerSlug, ids, onSuccess: onSuccessFromProps, selectAll, selectedFields, setSelectedFields, where } = props;
    const { permissions, user } = useAuth();
    const { code: locale } = useLocale();
    const { closeModal } = useModal();
    const { config: { routes: { api: apiRoute } } } = useConfig();
    const { getFormState } = useServerFunctions();
    const { i18n, t } = useTranslation();
    const [isInitializing, setIsInitializing] = useState(false);
    const router = useRouter();
    const abortFormStateRef = React.useRef(null);
    const collectionPermissions = permissions?.collections?.[collection.slug];
    const searchParams = useSearchParams();
    const select = useMemo(()=>{
        return unflatten(selectedFields.reduce((acc, option)=>{
            acc[option.value.path] = true;
            return acc;
        }, {}));
    }, [
        selectedFields
    ]);
    const onChange = useCallback(async ({ formState: prevFormState, submitted })=>{
        const controller = handleAbortRef(abortFormStateRef);
        const { state } = await getFormState({
            collectionSlug: collection.slug,
            docPermissions: collectionPermissions,
            docPreferences: null,
            formState: prevFormState,
            operation: 'update',
            schemaPath: collection.slug,
            select,
            signal: controller.signal,
            skipValidation: !submitted
        });
        abortFormStateRef.current = null;
        return state;
    }, [
        getFormState,
        collection,
        collectionPermissions,
        select
    ]);
    useEffect(()=>{
        const abortFormState = abortFormStateRef.current;
        return ()=>{
            abortAndIgnore(abortFormState);
        };
    }, []);
    const queryString = useMemo(()=>{
        const whereConstraints = [];
        if (where) {
            whereConstraints.push(where);
        }
        const queryWithSearch = mergeListSearchAndWhere({
            collectionConfig: collection,
            search: searchParams.get('search')
        });
        if (queryWithSearch) {
            whereConstraints.push(queryWithSearch);
        }
        if (selectAll) {
            // Match the current filter/search, or default to all docs
            whereConstraints.push(parseSearchParams(searchParams)?.where || {
                id: {
                    not_equals: ''
                }
            });
        } else {
            // If we're not selecting all, we need to select specific docs
            whereConstraints.push({
                id: {
                    in: ids || []
                }
            });
        }
        return qs.stringify({
            locale,
            select: {},
            where: combineWhereConstraints(whereConstraints)
        }, {
            addQueryPrefix: true
        });
    }, [
        collection,
        searchParams,
        selectAll,
        ids,
        locale,
        where
    ]);
    const onSuccess = ()=>{
        router.replace(qs.stringify({
            ...parseSearchParams(searchParams),
            _r: Date.now(),
            // Cache buster to force fresh data fetch. Prevents an e2e race condition where sometimes the data is not updated.
            page: selectAll ? '1' : undefined
        }, {
            addQueryPrefix: true
        }));
        closeModal(drawerSlug);
        if (typeof onSuccessFromProps === 'function') {
            onSuccessFromProps();
        }
    };
    const onFieldSelect = useCallback(async ({ dispatchFields, formState, selected })=>{
        setIsInitializing(true);
        setSelectedFields(selected || []);
        const { state } = await getFormState({
            collectionSlug: collection.slug,
            docPermissions: collectionPermissions,
            docPreferences: null,
            formState,
            operation: 'update',
            schemaPath: collection.slug,
            select: unflatten(selected.reduce((acc, option)=>{
                acc[option.value.path] = true;
                return acc;
            }, {})),
            skipValidation: true
        });
        dispatchFields({
            type: 'UPDATE_MANY',
            formState: state
        });
        setIsInitializing(false);
    }, [
        getFormState,
        collection.slug,
        collectionPermissions,
        setSelectedFields
    ]);
    return /*#__PURE__*/ _jsxDEV(DocumentInfoProvider, {
        collectionSlug: collection.slug,
        currentEditor: user,
        hasPublishedDoc: false,
        id: null,
        initialData: {},
        isLocked: false,
        lastUpdateTime: 0,
        mostRecentVersionIsAutosaved: false,
        unpublishedVersionCount: 0,
        versionCount: 0,
        children: /*#__PURE__*/ _jsxDEV(OperationContext, {
            value: "update",
            children: /*#__PURE__*/ _jsxDEV("div", {
                className: `${baseClass}__main`,
                children: [
                    /*#__PURE__*/ _jsxDEV("div", {
                        className: `${baseClass}__header`,
                        children: [
                            /*#__PURE__*/ _jsxDEV("h2", {
                                className: `${baseClass}__header__title`,
                                children: t('general:editingLabel', {
                                    count,
                                    label: getTranslation(count > 1 ? plural : singular, i18n)
                                })
                            }, void 0, false, {
                                fileName: "src/elements/EditMany/DrawerContent.tsx",
                                lineNumber: 335,
                                columnNumber: 13
                            }, this),
                            /*#__PURE__*/ _jsxDEV("button", {
                                "aria-label": t('general:close'),
                                className: `${baseClass}__header__close`,
                                id: `close-drawer__${drawerSlug}`,
                                onClick: ()=>closeModal(drawerSlug),
                                type: "button",
                                children: /*#__PURE__*/ _jsxDEV(XIcon, {}, void 0, false, {
                                    fileName: "src/elements/EditMany/DrawerContent.tsx",
                                    lineNumber: 348,
                                    columnNumber: 15
                                }, this)
                            }, void 0, false, {
                                fileName: "src/elements/EditMany/DrawerContent.tsx",
                                lineNumber: 341,
                                columnNumber: 13
                            }, this)
                        ]
                    }, void 0, true, {
                        fileName: "src/elements/EditMany/DrawerContent.tsx",
                        lineNumber: 334,
                        columnNumber: 11
                    }, this),
                    /*#__PURE__*/ _jsxDEV(Form, {
                        className: `${baseClass}__form`,
                        isInitializing: isInitializing,
                        onChange: [
                            onChange
                        ],
                        onSuccess: onSuccess,
                        children: [
                            /*#__PURE__*/ _jsxDEV(FieldSelect, {
                                fields: fields,
                                onChange: onFieldSelect,
                                permissions: collectionPermissions.fields
                            }, void 0, false, {
                                fileName: "src/elements/EditMany/DrawerContent.tsx",
                                lineNumber: 357,
                                columnNumber: 13
                            }, this),
                            selectedFields.length === 0 ? null : /*#__PURE__*/ _jsxDEV("div", {
                                className: "render-fields",
                                children: selectedFields.map((option, i)=>{
                                    const { value: { field, fieldPermissions, path } } = option;
                                    return /*#__PURE__*/ _jsxDEV(RenderField, {
                                        clientFieldConfig: field,
                                        indexPath: "",
                                        parentPath: "",
                                        parentSchemaPath: "",
                                        path: path,
                                        permissions: fieldPermissions
                                    }, `${path}-${i}`, false, {
                                        fileName: "src/elements/EditMany/DrawerContent.tsx",
                                        lineNumber: 370,
                                        columnNumber: 21
                                    }, this);
                                })
                            }, void 0, false, {
                                fileName: "src/elements/EditMany/DrawerContent.tsx",
                                lineNumber: 363,
                                columnNumber: 15
                            }, this),
                            /*#__PURE__*/ _jsxDEV("div", {
                                className: `${baseClass}__sidebar-wrap`,
                                children: /*#__PURE__*/ _jsxDEV("div", {
                                    className: `${baseClass}__sidebar`,
                                    children: /*#__PURE__*/ _jsxDEV("div", {
                                        className: `${baseClass}__sidebar-sticky-wrap`,
                                        children: /*#__PURE__*/ _jsxDEV("div", {
                                            className: `${baseClass}__document-actions`,
                                            children: collection?.versions?.drafts ? /*#__PURE__*/ _jsxDEV(React.Fragment, {
                                                children: [
                                                    /*#__PURE__*/ _jsxDEV(SaveDraftButton, {
                                                        action: formatAdminURL({
                                                            apiRoute,
                                                            path: `/${collection.slug}${queryString}&draft=true`
                                                        }),
                                                        disabled: selectedFields.length === 0
                                                    }, void 0, false, {
                                                        fileName: "src/elements/EditMany/DrawerContent.tsx",
                                                        lineNumber: 389,
                                                        columnNumber: 25
                                                    }, this),
                                                    /*#__PURE__*/ _jsxDEV(PublishButton, {
                                                        action: formatAdminURL({
                                                            apiRoute,
                                                            path: `/${collection.slug}${queryString}&draft=true`
                                                        }),
                                                        disabled: selectedFields.length === 0
                                                    }, void 0, false, {
                                                        fileName: "src/elements/EditMany/DrawerContent.tsx",
                                                        lineNumber: 396,
                                                        columnNumber: 25
                                                    }, this)
                                                ]
                                            }, void 0, true, {
                                                fileName: "src/elements/EditMany/DrawerContent.tsx",
                                                lineNumber: 388,
                                                columnNumber: 23
                                            }, this) : /*#__PURE__*/ _jsxDEV(Submit, {
                                                action: formatAdminURL({
                                                    apiRoute,
                                                    path: `/${collection.slug}${queryString}`
                                                }),
                                                disabled: selectedFields.length === 0
                                            }, void 0, false, {
                                                fileName: "src/elements/EditMany/DrawerContent.tsx",
                                                lineNumber: 405,
                                                columnNumber: 23
                                            }, this)
                                        }, void 0, false, {
                                            fileName: "src/elements/EditMany/DrawerContent.tsx",
                                            lineNumber: 386,
                                            columnNumber: 19
                                        }, this)
                                    }, void 0, false, {
                                        fileName: "src/elements/EditMany/DrawerContent.tsx",
                                        lineNumber: 385,
                                        columnNumber: 17
                                    }, this)
                                }, void 0, false, {
                                    fileName: "src/elements/EditMany/DrawerContent.tsx",
                                    lineNumber: 384,
                                    columnNumber: 15
                                }, this)
                            }, void 0, false, {
                                fileName: "src/elements/EditMany/DrawerContent.tsx",
                                lineNumber: 383,
                                columnNumber: 13
                            }, this)
                        ]
                    }, void 0, true, {
                        fileName: "src/elements/EditMany/DrawerContent.tsx",
                        lineNumber: 351,
                        columnNumber: 11
                    }, this)
                ]
            }, void 0, true, {
                fileName: "src/elements/EditMany/DrawerContent.tsx",
                lineNumber: 333,
                columnNumber: 9
            }, this)
        }, void 0, false, {
            fileName: "src/elements/EditMany/DrawerContent.tsx",
            lineNumber: 332,
            columnNumber: 7
        }, this)
    }, void 0, false, {
        fileName: "src/elements/EditMany/DrawerContent.tsx",
        lineNumber: 320,
        columnNumber: 5
    }, this);
};

//# sourceMappingURL=DrawerContent.js.map