/**
 * @license MIT
 * author: Cube Dev Team
 * @cube-dev/ui-kit v0.0.0-canary-43d3dd9
 * Released under the MIT license.
 */

import { useDebugValue, useId, useRef } from 'react';
import { useChainedCallback, useEvent } from '../../../../_internal/index.js';
import { mergeProps } from '../../../../utils/react/index.js';
import { warn } from '../../../../utils/warnings.js';
import { useInsideLegacyField } from '../Field.js';
import { useField } from './use-field.js';
export function useFieldProps(props, params = {}) {
    // We use ref here to "memoize" initial value
    const isDisabledRef = useRef(params.unsafe__isDisabled ?? false);
    const { valuePropsMapper = ({ value, onChange }) => {
        return {
            value: value ?? null,
            onChange,
        };
    }, defaultValidationTrigger = 'onBlur', } = params;
    const isInsideLegacyField = useInsideLegacyField();
    // useWarn(isInsideLegacyField, {
    //   key: 'use-field-props',
    //   args: ['<Field /> is deprecated, use component without <Field /> instead.'],
    // });
    if (props.rules && !props.name) {
        warn(`The "rules" prop is not suitable for fields that are not part of a form. Use "name" prop to link the field to a form.`);
    }
    if (isInsideLegacyField || isDisabledRef.current === true) {
        return props;
    }
    // For standalone fields (no name), just generate an ID without calling useField
    const hasName = props.name != null;
    const generatedId = useId();
    if (!hasName) {
        // Standalone field - just add generated ID if not provided
        if (!props.id) {
            const result = { ...props, id: generatedId };
            if (result.id && !result.labelProps) {
                result.labelProps = { for: result.id };
            }
            else if (result.id && result.labelProps && !result.labelProps.for) {
                result.labelProps = { ...result.labelProps, for: result.id };
            }
            return result;
        }
        return props;
    }
    // Form-connected field - use full useField logic
    const field = useField(props, {
        defaultValidationTrigger: params.defaultValidationTrigger,
    });
    const isOutsideOfForm = field?.form == null;
    if (props.rules && isOutsideOfForm) {
        warn(`The "rules" prop is not supported for fields that are not part of a form. The "${props.name}" field is placed outside the form.`);
    }
    const onBlurChained = useChainedCallback(field?.onBlur, 'onBlur' in props ? props.onBlur : undefined);
    const onChangeEvent = useEvent((value, dontTouch) => {
        field?.onChange?.(value, dontTouch, field?.validateTrigger ?? defaultValidationTrigger);
    });
    const valueProps = !isOutsideOfForm
        ? valuePropsMapper({
            value: field.value,
            onChange: onChangeEvent,
        })
        : {};
    if (isInsideLegacyField && !isOutsideOfForm) {
        const valuePropEventNames = !isOutsideOfForm
            ? Object.keys(valueProps).filter((name) => name.startsWith('on'))
            : [];
        for (const valuePropName of valuePropEventNames) {
            if (valuePropName in props) {
                warn(`The "${valuePropName}" listener is not supported for input "${props.name}" that is linked to a form via a <Field> component. Remove the <Field> component and move its properties to the input itself.`);
            }
        }
    }
    // Use errorMessage directly or fall back to validation errors
    const compiledErrorMessage = props.errorMessage !== undefined
        ? props.errorMessage
        : field?.field?.status === 'invalid' && field?.field?.errors?.length
            ? field.field.errors[0]
            : undefined;
    // Exclude 'form' from field to prevent it from being spread to DOM elements
    const { form: _form, ...fieldWithoutForm } = field ?? {};
    const result = isOutsideOfForm
        ? props
        : mergeProps(props, fieldWithoutForm, valueProps, {
            validateTrigger: field.validateTrigger ?? defaultValidationTrigger,
            onBlur: onBlurChained,
            errorMessage: compiledErrorMessage,
        });
    if (result.id) {
        if (!result.labelProps) {
            result.labelProps = {};
        }
        result.labelProps.for = result.id;
    }
    if (process.env.NODE_ENV === 'development') {
        useDebugValue(result);
    }
    return result;
}

        