'use client';
import { jsxDEV as _jsxDEV } from "react/jsx-dev-runtime";
import { getTranslation } from '@payloadcms/translations';
import { isNumber } from 'payload/shared';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { ReactSelect } from '../../elements/ReactSelect/index.js';
import { RenderCustomComponent } from '../../elements/RenderCustomComponent/index.js';
import { useField } from '../../forms/useField/index.js';
import { withCondition } from '../../forms/withCondition/index.js';
import { useTranslation } from '../../providers/Translation/index.js';
import { FieldDescription } from '../FieldDescription/index.js';
import { FieldError } from '../FieldError/index.js';
import { FieldLabel } from '../FieldLabel/index.js';
import { mergeFieldStyles } from '../mergeFieldStyles.js';
import './index.scss';
import { fieldBaseClass } from '../shared/index.js';
const NumberFieldComponent = (props)=>{
    const { field, field: { admin: { className, description, placeholder: placeholderFromProps, step = 1 } = {}, hasMany = false, label, localized, max = Infinity, maxRows = Infinity, min = -Infinity, required }, onChange: onChangeFromProps, path: pathFromProps, readOnly, validate } = props;
    const { i18n, t } = useTranslation();
    const memoizedValidate = useCallback((value, options)=>{
        if (typeof validate === 'function') {
            return validate(value, {
                ...options,
                max,
                min,
                required
            });
        }
    }, [
        validate,
        min,
        max,
        required
    ]);
    const { customComponents: { AfterInput, BeforeInput, Description, Error, Label } = {}, disabled, path, setValue, showError, value } = useField({
        potentiallyStalePath: pathFromProps,
        validate: memoizedValidate
    });
    const handleChange = useCallback((e)=>{
        const val = parseFloat(e.target.value);
        let newVal = val;
        if (Number.isNaN(val)) {
            newVal = null;
        }
        if (typeof onChangeFromProps === 'function') {
            onChangeFromProps(newVal);
        }
        setValue(newVal);
    }, [
        onChangeFromProps,
        setValue
    ]);
    const [valueToRender, setValueToRender] = useState([]);
    // Only for hasMany
    const handleHasManyChange = useCallback((selectedOption)=>{
        if (!(readOnly || disabled)) {
            let newValue;
            if (!selectedOption) {
                newValue = [];
            } else if (Array.isArray(selectedOption)) {
                newValue = selectedOption.map((option)=>Number(option.value?.value || option.value));
            } else {
                newValue = [
                    Number(selectedOption.value?.value || selectedOption.value)
                ];
            }
            setValue(newValue);
        }
    }, [
        readOnly,
        disabled,
        setValue
    ]);
    // useEffect update valueToRender:
    useEffect(()=>{
        if (hasMany && Array.isArray(value)) {
            setValueToRender(value.map((val, index)=>{
                return {
                    id: `${val}${index}`,
                    // append index to avoid duplicate keys but allow duplicate numbers
                    label: `${val}`,
                    value: {
                        toString: ()=>`${val}${index}`,
                        value: val?.value || val
                    }
                };
            }));
        }
    }, // You're probably wondering, why the hell is this done that way? Well, React-select automatically uses "label-value" as a key, so we will get that react duplicate key warning if we just pass in the value as multiple values can be the same. So we need to append the index to the toString() of the value to avoid that warning, as it uses that as the key.
    [
        value,
        hasMany
    ]);
    const styles = useMemo(()=>mergeFieldStyles(field), [
        field
    ]);
    const placeholder = getTranslation(placeholderFromProps, i18n);
    return /*#__PURE__*/ _jsxDEV("div", {
        className: [
            fieldBaseClass,
            'number',
            className,
            showError && 'error',
            (readOnly || disabled) && 'read-only',
            hasMany && 'has-many'
        ].filter(Boolean).join(' '),
        style: styles,
        children: [
            /*#__PURE__*/ _jsxDEV(RenderCustomComponent, {
                CustomComponent: Label,
                Fallback: /*#__PURE__*/ _jsxDEV(FieldLabel, {
                    label: label,
                    localized: localized,
                    path: path,
                    required: required
                }, void 0, false, {
                    fileName: "src/fields/Number/index.tsx",
                    lineNumber: 148,
                    columnNumber: 11
                }, void 0)
            }, void 0, false, {
                fileName: "src/fields/Number/index.tsx",
                lineNumber: 145,
                columnNumber: 7
            }, this),
            /*#__PURE__*/ _jsxDEV("div", {
                className: `${fieldBaseClass}__wrap`,
                children: [
                    /*#__PURE__*/ _jsxDEV(RenderCustomComponent, {
                        CustomComponent: Error,
                        Fallback: /*#__PURE__*/ _jsxDEV(FieldError, {
                            path: path,
                            showError: showError
                        }, void 0, false, {
                            fileName: "src/fields/Number/index.tsx",
                            lineNumber: 154,
                            columnNumber: 21
                        }, void 0)
                    }, void 0, false, {
                        fileName: "src/fields/Number/index.tsx",
                        lineNumber: 152,
                        columnNumber: 9
                    }, this),
                    BeforeInput,
                    hasMany ? /*#__PURE__*/ _jsxDEV(ReactSelect, {
                        className: `field-${path.replace(/\./g, '__')}`,
                        disabled: readOnly || disabled,
                        filterOption: (_, rawInput)=>{
                            const isOverHasMany = Array.isArray(value) && value.length >= maxRows;
                            return isNumber(rawInput) && !isOverHasMany;
                        },
                        isClearable: true,
                        isCreatable: true,
                        isMulti: true,
                        isSortable: true,
                        noOptionsMessage: ()=>{
                            const isOverHasMany = Array.isArray(value) && value.length >= maxRows;
                            if (isOverHasMany) {
                                return t('validation:limitReached', {
                                    max: maxRows,
                                    value: value.length + 1
                                });
                            }
                            return null;
                        },
                        // numberOnly
                        onChange: handleHasManyChange,
                        options: [],
                        placeholder: placeholder,
                        showError: showError,
                        value: valueToRender
                    }, void 0, false, {
                        fileName: "src/fields/Number/index.tsx",
                        lineNumber: 158,
                        columnNumber: 11
                    }, this) : /*#__PURE__*/ _jsxDEV("div", {
                        children: /*#__PURE__*/ _jsxDEV("input", {
                            disabled: readOnly || disabled,
                            id: `field-${path.replace(/\./g, '__')}`,
                            max: max,
                            min: min,
                            name: path,
                            onChange: handleChange,
                            onWheel: (e)=>{
                                // @ts-expect-error
                                e.target.blur();
                            },
                            placeholder: placeholder,
                            step: step,
                            type: "number",
                            value: typeof value === 'number' ? value : ''
                        }, void 0, false, {
                            fileName: "src/fields/Number/index.tsx",
                            lineNumber: 185,
                            columnNumber: 13
                        }, this)
                    }, void 0, false, {
                        fileName: "src/fields/Number/index.tsx",
                        lineNumber: 184,
                        columnNumber: 11
                    }, this),
                    AfterInput,
                    /*#__PURE__*/ _jsxDEV(RenderCustomComponent, {
                        CustomComponent: Description,
                        Fallback: /*#__PURE__*/ _jsxDEV(FieldDescription, {
                            description: description,
                            path: path
                        }, void 0, false, {
                            fileName: "src/fields/Number/index.tsx",
                            lineNumber: 206,
                            columnNumber: 21
                        }, void 0)
                    }, void 0, false, {
                        fileName: "src/fields/Number/index.tsx",
                        lineNumber: 204,
                        columnNumber: 9
                    }, this)
                ]
            }, void 0, true, {
                fileName: "src/fields/Number/index.tsx",
                lineNumber: 151,
                columnNumber: 7
            }, this)
        ]
    }, void 0, true, {
        fileName: "src/fields/Number/index.tsx",
        lineNumber: 132,
        columnNumber: 5
    }, this);
};
export const NumberField = withCondition(NumberFieldComponent);

//# sourceMappingURL=index.js.map