import { Theme } from '@mui/material/styles';
import { ReactNode } from 'react';
import { Sizes } from '@m4l/styles';
import { SemanticWidthOptions } from '../PropertyValue/types';
import { DynamicFormSlots } from './slots';
import { DYNAMIC_FORM_KEY_COMPONENT } from './constants';
import { M4LOverridesStyleRules } from '../../@types/augmentations';
import { FormStatusLoad, RHFormValues, RHFormProviderRef, ValidationSchema as RHFormValidationSchema } from '../hook-form/RHFormProvider/types';
import { ActionsFormIntroProps } from '../CommonActions/components/ActionFormIntro/types';
import { DateTimeRangePickerProps } from '../DateTimeRangePicker/types';
import { DaysOfWeekPickerProps } from '../DaysOfWeekPicker/types';
import { RHFCheckboxProps } from '../hook-form/RHFCheckbox/types';
import { RHFCheckableListProps } from '../hook-form/RHFCheckableList/types';
import { RHFNumberInputProps } from '../hook-form/RHFNumberInput/types';
import { RHFRadioGroupProps } from '../hook-form/RHFRadioGroup/types';
import { RHFSelectProps } from '../hook-form/RHFSelect/types';
import { RHFTextFieldProps } from '../hook-form/RHFTextField/types';
import { BaseRHFProps } from '../../hocs/withRHFController/types';
import { ImageSelectorProps } from '../ImageSelector/types';
/**
 * API contract type: FormMetadata
 */
export interface FormMetadata {
    id: number;
    name: string;
    version: number;
    label: string | null;
    description: string | null;
    iconId?: string | null;
    /** @deprecated Use `label`. */
    labelForm?: string;
    /** @deprecated Use `description`. */
    descriptionForm?: string;
}
/**
 * Subset of `RHFCheckboxProps` allowed from the backend via `fieldType.componentProps`.
 * Visible label, mandatory state, and field helper text are **not** defined here; they come from
 * {@link Field} (`label`, `mandatory`, `helperMessage`) and `resolveFieldInputLabel`, not from this payload.
 */
export type RHFCheckboxRHFComponentPropsFromBackend = Pick<RHFCheckboxProps, 'id' | 'htmlFor' | 'inlineText' | 'helperText' | 'error'>;
/**
 * Subset of props accepted from the backend for `RHFDateRangePicker` via `fieldType.componentProps`.
 * Visible label and field-level helper copy are **not** defined here; they come from {@link Field} and
 * `resolveFieldInputLabel`, not from this payload.
 */
export type RHFDateTimeRangePickerRHFComponentPropsFromBackend = Pick<BaseRHFProps, 'name'> & Pick<DateTimeRangePickerProps, 'calendars' | 'compact' | 'openOnFocus' | 'readOnly' | 'timeDisplayVariant'>;
/**
 * Subset of props accepted from the backend for `RHFDaysOfWeekPicker` via `fieldType.componentProps`.
 * Visible label and field-level helper copy are **not** defined here; they come from {@link Field} and
 * `resolveFieldInputLabel`, not from this payload.
 */
export type RHFDaysOfWeekPickerRHFComponentPropsFromBackend = Pick<BaseRHFProps, 'name'> & Pick<DaysOfWeekPickerProps, 'disabledDays' | 'readOnly' | 'multiple'>;
/**
 * Subset of `RHFNumberInputProps` allowed from the backend via `fieldType.componentProps`.
 * Visible label and field-level helper copy are **not** defined here; they come from {@link Field} and
 * `resolveFieldInputLabel`, not from this payload.
 */
export type RHFNumberInputRHFComponentPropsFromBackend = Pick<RHFNumberInputProps, 'min' | 'max' | 'step' | 'shiftMultiplier' | 'defaultValue' | 'withDecimal' | 'readOnly' | 'error' | 'id' | 'placeholder'>;
/**
 * Subset of `RHFRadioGroupProps` allowed from the backend via `fieldType.componentProps`.
 * Visible label and field-level helper copy are **not** defined here; they come from {@link Field} and
 * `resolveFieldInputLabel`, not from this payload. **`options`**, **`getOptionLabel`**, and **`getOptionValue`**
 * are not taken from the API (options from `field.options` / fetched options; resolvers from the radio-group normalizer).
 * **`optionLabelPath`** and **`optionValuePath`** are optional dot paths (e.g. `user.name`) resolved with
 * `getPropertyByString` from `@m4l/core` when building those resolvers.
 * @see RHFRadioGroupProps — `row` comes from MUI `RadioGroupProps` / `FormGroupProps`.
 */
export type RHFRadioGroupRHFComponentPropsFromBackend = Pick<RHFRadioGroupProps<unknown>, 'id' | 'row' | 'rowColumns'> & {
    optionLabelPath?: string;
    optionValuePath?: string;
};
/**
 * Subset of `RHFSelectProps` allowed from the backend via `fieldType.componentProps`.
 * Visible label and field-level helper copy are **not** defined here; they come from {@link Field} and
 * `resolveFieldInputLabel`, not from this payload.
 * **`options`** are not taken from the API (they come from `field.options` / fetched options). For multi-select,
 * use `isMultiple: true` in `componentProps` (not part of this pick); `multiple` on the payload is handled by the normalizer when valid.
 */
export type RHFSelectRHFComponentPropsFromBackend = Pick<RHFSelectProps<string | number, boolean | undefined>, 'id' | 'placeholder' | 'multiple'>;
/**
 * Subset of `RHFTextFieldProps` allowed from the backend via `fieldType.componentProps`.
 * Visible label and field-level helper copy are **not** defined here; they come from {@link Field} and
 * `resolveFieldInputLabel`, not from this payload.
 * Does not pass `InputProps` from normalized output (controlled in code).
 * paths into `Icon` React elements using environment asset prefixes.
 */
export type RHFTextFieldRHFComponentPropsFromBackend = Pick<RHFTextFieldProps, 'id' | 'htmlFor' | 'placeholder' | 'maxLength' | 'multiline' | 'rows' | 'minRows' | 'maxRows'> & {
    startIcon?: string;
    endIcon?: string;
};
/**
 * DynamicForm autocomplete metadata accepted from the backend via `fieldType.componentProps`.
 * Visible label and field-level helper copy are **not** defined here; they come from {@link Field} and
 * `resolveFieldInputLabel`, not from this payload.
 */
export interface RHFAutocompleteRHFComponentPropsFromBackend {
    optionLabelPath?: string;
    equalToValuePath?: string;
    isMultiple?: boolean;
    /**
     * Dot-path expression on each option (e.g. `startAdornment` or `data.icon`); the string value at that
     * path is the asset path, joined with `host_api_remote` when relative (same rules as RHFSelect option icons).
     */
    optionEndAdornmentIconPath?: string;
    optionEndAdornmentImagePath?: string;
    optionStartAdornmentIconPath?: string;
    optionStartAdornmentImagePath?: string;
}
/**
 * DynamicForm image-selector metadata accepted from the backend via `fieldType.componentProps`.
 * Visible label and field-level helper copy are **not** defined here; they come from {@link Field} and
 * `resolveFieldInputLabel`, not from this payload. Static `options` are taken from `field.options`, and
 * async option loading is driven by `field.endpoint` / `field.endpointParams`.
 */
export type RHFImageSelectorRHFComponentPropsFromBackend = Pick<ImageSelectorProps<unknown>, 'id' | 'presentationType' | 'imageSize' | 'maxColumns' | 'maxRows' | 'refetchOnOpen' | 'timeout' | 'resultField'> & {
    optionLabelPath?: string;
    optionImagePath?: string;
    equalToValuePath?: string;
};
/**
 * Output shape of `normalizeCheckableListPropsFromBackend` (whitelist): only JSON-safe props accepted for
 * `RHFCheckableList` from `field.fieldType.componentProps`. Raw `items` in `componentProps` and `size`
 * are not taken from the API; flat options are normalized from `field.options` into
 * `resolvedCheckableListItems` on the normalizer result. The normalizer also returns `resolvedLabel`,
 * `hasGroups`, and `resolvedSearchable` (see `NormalizedCheckableListPropsFromBackendResult`). Root UI props
 * such as `variant`, `loading`, `ariaLabel`, `ariaLabelledBy`, `className`, `dataTestId`, and `id` are not
 * read from `componentProps`; set them in application code if needed.
 */
export type NormalizedRHFCheckableListPropsFromBackend = Pick<RHFCheckableListProps, 'groups' | 'searchable' | 'multiple' | 'selectAll' | 'groupable' | 'expandAllGroups' | 'itemRowHeight' | 'groupRowHeight' | 'width' | 'checkboxSize' | 'showCheckboxOnGroup' | 'indeterminateBehavior'>;
/**
 * Loose backend payload shape accepted for `fieldType.componentProps` before each normalizer validates it.
 */
export type DynamicFormBackendPropValue = unknown;
/**
 * Combined type used by DynamicForm normalize helpers: JSON-safe props allowed under `fieldType.componentProps`.
 * It intentionally **excludes** control label/mandatory/helper messaging; those come from {@link Field} and dictionary
 * resolution (`resolveFieldInputLabel`), not from this object. Extra backend keys are tolerated at the type level
 * because each normalizer already whitelists supported keys and validates runtime value types before use.
 */
export type CombinedFieldComponentPropsFromBackend = Partial<RHFCheckboxRHFComponentPropsFromBackend> & Partial<RHFDateTimeRangePickerRHFComponentPropsFromBackend> & Partial<RHFDaysOfWeekPickerRHFComponentPropsFromBackend> & Partial<RHFNumberInputRHFComponentPropsFromBackend> & Partial<RHFRadioGroupRHFComponentPropsFromBackend> & Partial<RHFSelectRHFComponentPropsFromBackend> & Partial<RHFTextFieldRHFComponentPropsFromBackend> & Partial<RHFAutocompleteRHFComponentPropsFromBackend> & Partial<RHFImageSelectorRHFComponentPropsFromBackend> & Partial<NormalizedRHFCheckableListPropsFromBackend> & {
    [key: string]: DynamicFormBackendPropValue;
};
/** @deprecated Use `CombinedFieldComponentPropsFromBackend`. */
export type combinatedRHFComponentsProps = CombinedFieldComponentPropsFromBackend;
/**
 * API contract type: FieldType
 */
export interface FieldType {
    id: string;
    name: string;
    componentId: string;
    componentProps?: CombinedFieldComponentPropsFromBackend;
    /** @deprecated Use `componentProps`. */
    rhfComponentProps?: CombinedFieldComponentPropsFromBackend;
    supportsOptions: boolean;
    supportsValidation: boolean;
}
/**
 * API contract type: ValidationType
 */
export interface ValidationType {
    id: string;
    name: string;
    requiresValue: boolean;
    /**
     * Validation message for this rule (API field `errorMessageForm`): dictionary id (numeric string)
     * resolved via `getLabel`, or display-ready copy when the backend sends the final string.
     */
    errorMessageForm: string;
}
/**
 * API contract type: FieldValidation
 */
export interface FieldValidation {
    id: string;
    isActive: boolean;
    displayOrder: number;
    validationType?: ValidationType;
    type?: ValidationType;
    value?: string;
}
/**
 * API contract type: FieldOption
 */
export interface FieldOption {
    id: number;
    name: string | null;
    value: string;
    isDefault: boolean;
    displayOrder: number;
}
export type FieldCurrentValue = boolean | number | string | number[] | string[];
/**
 * Optional field-level metadata carried inside each field entry.
 * Drives layout hints resolved by DynamicFormContent (e.g. flex-wrap item sizing).
 */
export interface FieldMetadata {
    /**
     * Semantic layout width for the field wrapper in the form flex-wrap container.
     * Maps to the same `SemanticWidthOptions` used by `PropertyValue`, so field wrappers
     * share the same preferred widths as ContainerFlow-style semantic items while still
     * allowing rows to redistribute leftover space more naturally.
     * When `null` or absent the field wrapper spans the full available width.
     */
    semanticWidth?: SemanticWidthOptions;
}
/**
 * API contract type: measurement unit attached to a field (API key `magnitude_unit`).
 * `symbol` is forwarded to the field label through Label's `symbol` prop and rendered
 * in parentheses after the label text (e.g. `Temperatura (°C)`).
 */
export interface MagnitudeUnit {
    id: string;
    symbol: string | null;
}
/**
 * API contract type: dynamic form field definition (metadata, value, validation, visibility).
 */
export interface Field {
    /** Unique identifier for the field (e.g. used as React key and in conditional rules). */
    id: number;
    /** Form key used as the field name in the form state and in validation schema. */
    name: string;
    /** Options for select/checkable-list type fields; empty for other types. */
    options: unknown[];
    /** Type and RHF component to render (e.g. RHFTextField, RHFSelect) and component props. */
    fieldType: FieldType;
    /**
     * GET URL for option-list fetch (RHFSelect, RHFCheckableList, RHFRadioGroup via `useFieldsWithFetchedOptions`)
     * or for RHFAutoComplete async requests when set.
     */
    endpoint?: string;
    /**
     * Static query parameters for the option-list GET or for RHFAutocompleteAsync (merged into the request).
     */
    endpointParams?: Record<string, unknown>;
    /**
     * Query filter field name when the user types text and the compared value is a string (`o1` in `f`).
     */
    endpointFilterFieldValueString?: string;
    /**
     * Query filter field name when the user types a numeric value (`o1` in `f` as number).
     */
    endpointFilterFieldValueNumber?: string;
    /**
     * Query filter field name when the user types free text for the option label (`o1` in `f`).
     */
    endpointFilterFieldLabel?: string;
    /**
     * Measurement unit for the field (API key `magnitude_unit`). When `symbol` is a
     * non-empty string it is shown in parentheses after the label; falsy values omit it.
     */
    magnitudeUnit?: MagnitudeUnit | null;
    /** Optional help text shown below the field. */
    helperMessage: string | null;
    /** @deprecated Use `helperMessage`. */
    helperText?: string | null;
    /** When true, the field is required and validation schema enforces it when visible. */
    mandatory: boolean;
    /** @deprecated Use `mandatory`. */
    isRequired?: boolean;
    /** Placeholder for text/input-like components. */
    placeholder: string | null;
    /** Backend property identifier (e.g. for persistence or API mapping). */
    propertyId: string;
    /** Validation rules (min, max, minLength, email, etc.) applied when the field is visible. */
    validations: FieldValidation[];
    /** Current value from the API. */
    currentValue: FieldCurrentValue | null;
    /** Fallback value when currentValue is null; used by resolveInitialValue. */
    defaultValue: boolean | number | string | null;
    /** Order of the field in the form; visible fields are sorted by this for rendering. */
    displayOrder: number;
    /** Initial visibility from API for non-conditional fields. */
    isVisible: boolean | null;
    /** Visibility reason from API (for debugging/traceability). */
    visibilityReason: string | null;
    /** When true, visibility is controlled by conditional rules; otherwise by isVisible. */
    isConditional: boolean;
    /** Server-side validation errors, if any (e.g. from a previous submit). */
    validationErrors: unknown[];
    /**
     * Visible label text when the API sends a non-empty string; otherwise `resolveFieldInputLabel`
     * uses `dynamic_form.label_not_found_message` with the field id.
     */
    label: string | null;
    /** @deprecated Use `label`. */
    fieldLabel?: string;
    /** Dictionary key for the field description (i18n). */
    description: string | null;
    /** @deprecated Use `description`. */
    fieldDescription?: string;
    /**
     * Optional field-level metadata from the API (e.g. `{ semanticWidth: 'bigName' }`).
     * `metadata.semanticWidth` drives the preferred flex width in `DynamicFormContent`,
     * using the same semantic catalog as `PropertyValue` while allowing rows to redistribute
     * remaining space more naturally.
     * When `null` or absent the field wrapper defaults to full available width.
     */
    metadata?: FieldMetadata | null;
}
/**
 * API contract type: ConditionalRuleOperator
 */
export interface ConditionalRuleOperator {
    id: string;
    name: string;
    /**
     * Dictionary key for the operator name (i18n).
     * @deprecated Not used anymore.
     */
    nameDictionaryId: number;
}
/**
 * API contract type: rule that controls visibility of a target field based on a source field value.
 * Used by useDynamicFormConditionals (visibility) and useDynamicForm (validation schema .when()).
 */
export interface ConditionalRule {
    /** Unique identifier for the rule. */
    id: string;
    /** Operator used to compare source value with conditionValue (e.g. equals, greater_than, contains). */
    operator: ConditionalRuleOperator;
    /** When false, the rule is ignored for visibility and validation. */
    isActive: boolean;
    /** If 'show': target is visible when condition is met. If 'hide': target is visible when condition is not met. */
    actionType: 'show' | 'hide';
    /** Display/priority order of the rule (e.g. for ordering multiple rules). */
    displayOrder: number;
    /** Value compared against the source field value (right-hand side of the operator). */
    conditionValue: string;
    /** API id of the field whose value is watched to evaluate the condition. */
    sourceFieldId: number;
    /** API id of the field whose visibility is controlled by this rule. */
    targetFieldId: number;
    /** Form key of the source field; used to read the current value (e.g. watchValues[sourceFieldName]). */
    sourceFieldName: string;
    /** Form key of the target field; used to add/remove from visible fields and to build validation deps. */
    targetFieldName: string;
}
/**
 * API contract type: FormInstance
 */
export interface FormInstance {
    id: number;
    name: string | null;
    createdAt: string;
    updatedAt: string;
    resourceTypeId: string | null;
    resourceSerialId: string | null;
}
/**
 * API contract type: DynamicFormApiResponse
 */
export interface DynamicFormApiResponse {
    form: FormMetadata;
    fields: Field[];
    instance: FormInstance | null;
    conditionalRules: ConditionalRule[];
}
/**
 * Submit strategy for the decoupled DynamicForm.
 * - `'form'`: single request with the whole payload to `outputEndpoint` (current default behavior).
 * - `'perField'`: one request per field to `forms/instances/{instanceId}/fields/{fieldId}/values`,
 *   all executed concurrently via `Promise.all`. Transitional mode while the backend does not
 *   support saving the complete form in a single endpoint.
 */
export type DynamicFormSubmitMode = 'form' | 'perField';
/**
 * Visual feedback state shown after a decoupled DynamicForm submit attempt.
 */
export type DynamicFormSubmitFeedbackStatus = 'success' | 'error';
/**
 * Base props shared by DynamicForm in both coupled and decoupled modes.
 */
interface DynamicFormPropsBase {
    /**
     * Form type ID.
     */
    formId?: number;
    /**
     * Form instance ID.
     */
    formInstanceId?: number;
    /**
     * Input endpoint for fetching form data.
     */
    inputEndpoint?: string;
    /**
     * Output endpoint for submitting form data.
     */
    outputEndpoint?: string;
    /**
     * Submit strategy. `'form'` (default) sends one request to `outputEndpoint`;
     * `'perField'` sends one POST per field to `forms/instances/{instanceId}/fields/{fieldId}/values`
     * concurrently (`Promise.all`). Per-field mode requires a resolvable instance id
     * (`formInstanceId` prop or `instance.id` from the loaded form data).
     * Only used when coupled is false (decoupled mode).
     */
    submitMode?: DynamicFormSubmitMode;
    /**
     * Function to format data received from the input endpoint.
     * May return the already-typed DynamicForm contract or a plain record.
     */
    formatInputData?: (data: Record<string, unknown>) => Record<string, unknown> | DynamicFormApiResponse;
    /**
     * Function to format data before sending to the output endpoint.
     */
    formatOutputData?: (data: Record<string, unknown>) => Record<string, unknown>;
    /**
     * Callback invoked when the form is submitted with validated data.
     */
    onSubmit?: (data: Record<string, unknown>) => void | Promise<void>;
    /**
     * Callback invoked when form validation fails.
     */
    onSubmitError?: (errors: Record<string, unknown>) => void;
    /**
     * Component size.
     */
    size?: Extract<Sizes, 'small' | 'medium'>;
    /**
     * Additional CSS class.
     */
    className?: string;
    /**
     * Test ID for QA.
     */
    dataTestId?: string;
    /**
     * Development-only metadata string rendered as a `data-meta` attribute on the form content
     * root. Intended for debugging which form/instance a rendered DynamicForm belongs to.
     * Not rendered in production builds (same gating as `dataTestId`).
     */
    dataMeta?: string;
    /**
     * Additional CSS class for each field wrapper.
     */
    fieldWrapperClassName?: string;
    /**
     * Props to customize ActionFormIntro.
     * Only used when coupled is false (decoupled mode).
     * If not provided, default values are used.
     */
    actionFormIntroProps?: Partial<ActionsFormIntroProps>;
    /**
     * Custom render for form actions.
     * Only used when coupled is false (decoupled mode).
     * If provided, replaces the default ActionsContainer and ActionFormIntro.
     */
    renderActions?: () => ReactNode;
}
/**
 * Props when coupled=false (decoupled mode). initialData, validationSchema and coupledStatusLoad are optional.
 */
export interface DynamicFormPropsDecoupled extends DynamicFormPropsBase {
    coupled?: false;
    /**
     * Initial form data. If provided, it is used instead of fetching from the endpoint.
     */
    initialData?: DynamicFormApiResponse | null;
    /**
     * Form validation schema.
     */
    validationSchema?: RHFormValidationSchema<DynamicFormValues>;
    /**
     * When coupled=true: load status from the consumer (e.g. useDynamicFormData statusLoad).
     */
    coupledStatusLoad?: FormStatusLoad;
}
/**
 * Props when coupled=true. coupledStatusLoad is required; initialData is optional so the parent
 * can pass already-fetched form data (e.g. from useDynamicFormCoupled) and avoid duplicate fetch.
 */
export interface DynamicFormPropsCoupled extends DynamicFormPropsBase {
    coupled: true;
    /**
     * Load status from the consumer (e.g. useDynamicFormData statusLoad). Required in coupled mode.
     */
    coupledStatusLoad: FormStatusLoad;
    /**
     * Pre-loaded form structure and values. When provided (e.g. from useDynamicFormCoupled),
     * DynamicForm uses it so the dynamic fields render without waiting for an internal fetch.
     */
    initialData?: DynamicFormApiResponse | null;
}
/**
 * DynamicForm component props.
 * When coupled=true, initialData, validationSchema and coupledStatusLoad are required.
 */
export type DynamicFormProps = DynamicFormPropsDecoupled | DynamicFormPropsCoupled;
/**
 * Owner state used to define internal style and behavior properties.
 */
export interface DynamicFormOwnerState extends Pick<DynamicFormProps, 'size'> {
    [key: string]: unknown;
}
/**
 * Available slot types for the component.
 */
export type DynamicFormSlotsType = keyof typeof DynamicFormSlots;
/**
 * Styles applicable to the component via theme and custom slots.
 */
export type DynamicFormStyles = M4LOverridesStyleRules<DynamicFormSlotsType, typeof DYNAMIC_FORM_KEY_COMPONENT, Theme>;
/**
 * Type for dynamic form values.
 */
export type DynamicFormValues = RHFormValues & Record<string, unknown>;
/**
 * Type for the value exposed when DynamicForm is coupled (coupled=true).
 * Contains field values and internal validation state.
 */
export interface DynamicFormFieldsValue {
    [fieldName: string]: unknown;
    isDynamicFormValidInternal: boolean;
}
/**
 * Type for methods exposed via DynamicForm ref.
 * Exposes RHFormProvider API for parent component access.
 */
export type DynamicFormRef = RHFormProviderRef<DynamicFormValues>;
/**
 * Props for the internal content that renders form fields. In coupled mode the component
 * must be used where RHFormProvider exists (provided by the parent at instantiation site).
 */
export interface DynamicFormContentProps {
    data: DynamicFormApiResponse;
    currentSize: 'small' | 'medium';
    fieldWrapperClassName?: string;
    dataTestId?: string;
    dataMeta?: string;
    coupled?: boolean;
    actionFormIntroProps?: Partial<DynamicFormProps['actionFormIntroProps']>;
    renderActions?: DynamicFormProps['renderActions'];
    submitFeedbackStatus?: DynamicFormSubmitFeedbackStatus | null;
}
export {};
//# sourceMappingURL=types.d.ts.map