function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
/*
 * Copyright 2025 Palantir Technologies, Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { useOsdkAction, useOsdkMetadata } from "@osdk/react";
import React, { useCallback, useEffect, useMemo } from "react";
import { typedReactMemo } from "../shared/typedMemo.js";
import { BaseForm } from "./BaseForm.js";
import { coerceFieldValue } from "./utils/coerceFieldValue.js";
import { getDefaultFieldDefinitions } from "./utils/getDefaultFieldDefinitions.js";
const EMPTY_FIELD_DEFINITIONS = [];
const EMPTY_FORM_CONTENT = [];
export const ActionForm = typedReactMemo(function ({
  actionDefinition,
  formTitle,
  showFormTitle = false,
  formFieldDefinitions,
  formState: controlledFormState,
  onFormStateChange,
  isSubmitDisabled,
  onSubmit,
  onValidationResponse: _onValidationResponse,
  onSuccess,
  onError
}) {
  const {
    applyAction: osdkApplyAction,
    isPending
  } = useOsdkAction(actionDefinition);
  const {
    metadata,
    loading: metadataLoading,
    error: metadataError
  } = useOsdkMetadata(actionDefinition);
  useEffect(function () {
    if (metadataError != null) {
      onError?.({
        type: "unknown",
        error: metadataError
      });
    }
  }, [metadataError, onError]);
  const parameters = metadata?.parameters;
  const customFieldDefinitions = useMemo(() => {
    if (formFieldDefinitions == null) {
      return null;
    }
    // RendererFieldDefinition is a discriminated union keyed by fieldComponent.
    // TypeScript can't verify that the spread preserves the fieldComponent ↔
    // fieldComponentProps pairing, but FormFieldDefinition guarantees it.
    return formFieldDefinitions.map(def => {
      const {
        defaultValue,
        ...fieldDefinition
      } = def;
      return {
        ...fieldDefinition,
        fieldKey: String(def.fieldKey),
        fieldType: parameters?.[String(def.fieldKey)]?.type,
        fieldComponentProps: defaultValue === undefined ? def.fieldComponentProps : {
          ...def.fieldComponentProps,
          defaultValue
        }
      };
    });
  }, [formFieldDefinitions, parameters]);
  const rendererFieldDefinitions = useMemo(() => customFieldDefinitions ?? (metadata != null ? getDefaultFieldDefinitions(metadata) : EMPTY_FIELD_DEFINITIONS), [customFieldDefinitions, metadata]);
  const formContent = useMemo(() => rendererFieldDefinitions.length === 0 ? EMPTY_FORM_CONTENT : rendererFieldDefinitions.map(def => ({
    type: "field",
    definition: def
  })), [rendererFieldDefinitions]);
  const coerceFormState = useCallback(rawState => {
    const coerced = {};
    for (const [key, value] of Object.entries(rawState)) {
      coerced[key] = coerceFieldValue(parameters?.[key]?.type, value);
    }
    return coerced;
  }, [parameters]);
  const handleSubmit = useCallback(async rawFormState => {
    const formState = coerceFormState(rawFormState);
    try {
      if (onSubmit != null) {
        await onSubmit(formState, osdkApplyAction);
      } else {
        const result = await osdkApplyAction(formState);
        onSuccess?.(result);
      }
    } catch (e) {
      onError?.({
        type: "submission",
        error: e
      });
    }
  }, [coerceFormState, onSubmit, osdkApplyAction, onSuccess, onError]);
  const handleFieldValueChange = useCallback((fieldKey, value) => {
    onFormStateChange?.(prev => ({
      ...prev,
      [fieldKey]: value
    }));
  }, [onFormStateChange]);
  const resolvedTitle = showFormTitle ? formTitle ?? metadata?.displayName ?? actionDefinition.apiName : undefined;
  const commonProps = {
    formTitle: resolvedTitle,
    formContent,
    onSubmit: handleSubmit,
    isSubmitDisabled,
    isPending,
    isLoading: metadataLoading,
    onFieldValueChange: handleFieldValueChange
  };
  if (!(controlledFormState != null)) {
    return /*#__PURE__*/React.createElement(BaseForm, commonProps);
  }
  return /*#__PURE__*/React.createElement(BaseForm, _extends({}, commonProps, {
    formState: controlledFormState
  }));
});

// The inner render fn is anonymous in the published build, so set a displayName
// on the memo wrapper for React DevTools and the OSDK devtools component tree.
ActionForm.displayName = "ActionForm";
//# sourceMappingURL=ActionForm.js.map