'use client';
import { jsxDEV as _jsxDEV } from "react/jsx-dev-runtime";
import { getTranslation } from '@payloadcms/translations';
import { transformWhereQuery, validateWhereQuery } from 'payload/shared';
import React, { useMemo } from 'react';
import { useAuth } from '../../providers/Auth/index.js';
import { useListQuery } from '../../providers/ListQuery/index.js';
import { useTranslation } from '../../providers/Translation/index.js';
import { reduceFieldsToOptions } from '../../utilities/reduceFieldsToOptions.js';
import { Button } from '../Button/index.js';
import { Condition } from './Condition/index.js';
import { fieldTypeConditions, getValidFieldOperators } from './field-types.js';
import './index.scss';
const baseClass = 'where-builder';
/**
 * The WhereBuilder component is used to render the filter controls for a collection's list view.
 * It is part of the {@link ListControls} component which is used to render the controls (search, filter, where).
 */ export const WhereBuilder = (props)=>{
    const { collectionPluralLabel, collectionSlug, fields, renderedFilters, resolvedFilterOptions } = props;
    const { i18n, t } = useTranslation();
    const { permissions } = useAuth();
    const fieldPermissions = permissions?.collections?.[collectionSlug]?.fields;
    const reducedFields = useMemo(()=>reduceFieldsToOptions({
            fieldPermissions,
            fields,
            i18n
        }), [
        fieldPermissions,
        fields,
        i18n
    ]);
    const { handleWhereChange, query } = useListQuery();
    const conditions = useMemo(()=>{
        const whereFromSearch = query.where;
        if (whereFromSearch) {
            if (validateWhereQuery(whereFromSearch)) {
                return whereFromSearch.or;
            }
            // Transform the where query to be in the right format. This will transform something simple like [text][equals]=example%20post to the right format
            const transformedWhere = transformWhereQuery(whereFromSearch);
            if (validateWhereQuery(transformedWhere)) {
                return transformedWhere.or;
            }
            console.warn(`Invalid where query in URL: ${JSON.stringify(whereFromSearch)}`);
        }
        // eslint-disable-line no-console
        return [];
    }, [
        query.where
    ]);
    const addCondition = React.useCallback(async ({ andIndex, field, orIndex, relation })=>{
        const newConditions = [
            ...conditions
        ];
        const defaultOperator = fieldTypeConditions[field.field.type].operators[0].value;
        if (relation === 'and') {
            newConditions[orIndex].and.splice(andIndex, 0, {
                [String(field.value)]: {
                    [defaultOperator]: undefined
                }
            });
        } else {
            newConditions.push({
                and: [
                    {
                        [String(field.value)]: {
                            [defaultOperator]: undefined
                        }
                    }
                ]
            });
        }
        await handleWhereChange({
            or: newConditions
        });
    }, [
        conditions,
        handleWhereChange
    ]);
    const updateCondition = React.useCallback(async ({ andIndex, field, operator: incomingOperator, orIndex, value })=>{
        const existingCondition = conditions[orIndex].and[andIndex];
        if (typeof existingCondition === 'object' && field.value) {
            const { validOperator } = getValidFieldOperators({
                field: field.field,
                operator: incomingOperator
            });
            const newRowCondition = {
                [String(field.value)]: {
                    [validOperator]: value
                }
            };
            const newConditions = [
                ...conditions
            ];
            newConditions[orIndex].and[andIndex] = newRowCondition;
            await handleWhereChange({
                or: newConditions
            });
        }
    }, [
        conditions,
        handleWhereChange
    ]);
    const removeCondition = React.useCallback(async ({ andIndex, orIndex })=>{
        const newConditions = [
            ...conditions
        ];
        newConditions[orIndex].and.splice(andIndex, 1);
        if (newConditions[orIndex].and.length === 0) {
            newConditions.splice(orIndex, 1);
        }
        await handleWhereChange({
            or: newConditions
        });
    }, [
        conditions,
        handleWhereChange
    ]);
    return /*#__PURE__*/ _jsxDEV("div", {
        className: baseClass,
        children: [
            conditions.length > 0 && /*#__PURE__*/ _jsxDEV(React.Fragment, {
                children: [
                    /*#__PURE__*/ _jsxDEV("p", {
                        className: `${baseClass}__label`,
                        children: t('general:filterWhere', {
                            label: getTranslation(collectionPluralLabel, i18n)
                        })
                    }, void 0, false, {
                        fileName: "src/elements/WhereBuilder/index.tsx",
                        lineNumber: 136,
                        columnNumber: 11
                    }, this),
                    /*#__PURE__*/ _jsxDEV("ul", {
                        className: `${baseClass}__or-filters`,
                        children: conditions.map((or, orIndex)=>{
                            const compoundOrKey = `${orIndex}_${Array.isArray(or?.and) ? or.and.length : ''}`;
                            return /*#__PURE__*/ _jsxDEV("li", {
                                children: [
                                    orIndex !== 0 && /*#__PURE__*/ _jsxDEV("div", {
                                        className: `${baseClass}__label`,
                                        children: t('general:or')
                                    }, void 0, false, {
                                        fileName: "src/elements/WhereBuilder/index.tsx",
                                        lineNumber: 145,
                                        columnNumber: 37
                                    }, this),
                                    /*#__PURE__*/ _jsxDEV("ul", {
                                        className: `${baseClass}__and-filters`,
                                        children: Array.isArray(or?.and) && or.and.map((_, andIndex)=>{
                                            const condition = conditions[orIndex].and[andIndex];
                                            const fieldPath = Object.keys(condition)[0];
                                            const operator = Object.keys(condition?.[fieldPath] || {})?.[0] || undefined;
                                            const value = condition?.[fieldPath]?.[operator] || undefined;
                                            return /*#__PURE__*/ _jsxDEV("li", {
                                                children: [
                                                    andIndex !== 0 && /*#__PURE__*/ _jsxDEV("div", {
                                                        className: `${baseClass}__label`,
                                                        children: t('general:and')
                                                    }, void 0, false, {
                                                        fileName: "src/elements/WhereBuilder/index.tsx",
                                                        lineNumber: 160,
                                                        columnNumber: 31
                                                    }, this),
                                                    /*#__PURE__*/ _jsxDEV(Condition, {
                                                        addCondition: addCondition,
                                                        andIndex: andIndex,
                                                        fieldPath: fieldPath,
                                                        filterOptions: resolvedFilterOptions?.get(fieldPath),
                                                        operator: operator,
                                                        orIndex: orIndex,
                                                        reducedFields: reducedFields,
                                                        removeCondition: removeCondition,
                                                        RenderedFilter: renderedFilters?.get(fieldPath),
                                                        updateCondition: updateCondition,
                                                        value: value
                                                    }, void 0, false, {
                                                        fileName: "src/elements/WhereBuilder/index.tsx",
                                                        lineNumber: 162,
                                                        columnNumber: 29
                                                    }, this)
                                                ]
                                            }, andIndex, true, {
                                                fileName: "src/elements/WhereBuilder/index.tsx",
                                                lineNumber: 158,
                                                columnNumber: 27
                                            }, this);
                                        })
                                    }, void 0, false, {
                                        fileName: "src/elements/WhereBuilder/index.tsx",
                                        lineNumber: 146,
                                        columnNumber: 19
                                    }, this)
                                ]
                            }, compoundOrKey, true, {
                                fileName: "src/elements/WhereBuilder/index.tsx",
                                lineNumber: 144,
                                columnNumber: 17
                            }, this);
                        })
                    }, void 0, false, {
                        fileName: "src/elements/WhereBuilder/index.tsx",
                        lineNumber: 139,
                        columnNumber: 11
                    }, this),
                    /*#__PURE__*/ _jsxDEV(Button, {
                        buttonStyle: "icon-label",
                        className: `${baseClass}__add-or`,
                        icon: "plus",
                        iconPosition: "left",
                        iconStyle: "with-border",
                        onClick: async ()=>{
                            await addCondition({
                                andIndex: 0,
                                field: reducedFields.find((field)=>!field.field.admin?.disableListFilter),
                                orIndex: conditions.length,
                                relation: 'or'
                            });
                        },
                        children: t('general:or')
                    }, void 0, false, {
                        fileName: "src/elements/WhereBuilder/index.tsx",
                        lineNumber: 183,
                        columnNumber: 11
                    }, this)
                ]
            }, void 0, true, {
                fileName: "src/elements/WhereBuilder/index.tsx",
                lineNumber: 135,
                columnNumber: 9
            }, this),
            conditions.length === 0 && /*#__PURE__*/ _jsxDEV("div", {
                className: `${baseClass}__no-filters`,
                children: [
                    /*#__PURE__*/ _jsxDEV("div", {
                        className: `${baseClass}__label`,
                        children: t('general:noFiltersSet')
                    }, void 0, false, {
                        fileName: "src/elements/WhereBuilder/index.tsx",
                        lineNumber: 204,
                        columnNumber: 11
                    }, this),
                    /*#__PURE__*/ _jsxDEV(Button, {
                        buttonStyle: "icon-label",
                        className: `${baseClass}__add-first-filter`,
                        icon: "plus",
                        iconPosition: "left",
                        iconStyle: "with-border",
                        onClick: async ()=>{
                            if (reducedFields.length > 0) {
                                await addCondition({
                                    andIndex: 0,
                                    field: reducedFields.find((field)=>!field.field.admin?.disableListFilter),
                                    orIndex: conditions.length,
                                    relation: 'or'
                                });
                            }
                        },
                        children: t('general:addFilter')
                    }, void 0, false, {
                        fileName: "src/elements/WhereBuilder/index.tsx",
                        lineNumber: 205,
                        columnNumber: 11
                    }, this)
                ]
            }, void 0, true, {
                fileName: "src/elements/WhereBuilder/index.tsx",
                lineNumber: 203,
                columnNumber: 9
            }, this)
        ]
    }, void 0, true, {
        fileName: "src/elements/WhereBuilder/index.tsx",
        lineNumber: 133,
        columnNumber: 5
    }, this);
};

//# sourceMappingURL=index.js.map