'use strict';
'use client';
import { jsx, jsxs } from 'react/jsx-runtime';
import { useState, useRef, useEffect, useImperativeHandle } from 'react';
import { getInitialEditResource, getSyncedEditResourceConfig, onConfigChange, initializeMultiListResources, getEditNavigationItems, onSaveResourceOnChange, shouldShowSaveCancelButtons, onCancelImageEdit } from './EditResource.funcs.js';
import { useAsyncEffect } from '../../../fd-toolbox/hooks/use-async-effect.js';
import { useForm, FormProvider } from 'react-hook-form';
import { isReadOnlyResource } from '../resource-list/resource-list-checkers.js';
import { useSaveComplete } from './save-complete-context.js';
import { useEditResourceConfig } from './services/use-edit-resource-config.js';
import { editResourceLayoutTypes } from './edit-resource-constants.js';
import { getMultiListConfig } from '../components/multi-list/multi-list-config.js';
import { isUuidSet } from '../../../fd-toolbox/functions/value-checking-functions.js';
import { EditResourceTabs } from './EditResourceTabs.js';
import { cn } from '../../../fd-toolbox/lib/utils.js';
import { EditResourceHeader } from './EditResourceHeader.js';
import { shouldShowTabs, deleteResource, shouldEditResourceShowDeleteButton } from './services/edit-resources.js';
import { EditResourceFormBody } from './EditResourceFormBody.js';
import { Navigation } from '../../fd-component-toolbox/navigation/Navigation.js';
import { useGlobalConfig } from '../providers/global-provider/GlobalContext.js';
import { useEditResourceRef } from './hooks/use-edit-resource-ref.js';
import { useElementId } from '../../../fd-toolbox/hooks/use-element-id.js';
import { formMethods } from '../../../base-repo/constants/tools-constants.js';
import { onEditResourceValidation, onResourceSave } from './services/edit-resource-save.js';

var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", {
  value,
  configurable: true
});
const instanceNumber = {
  value: 0
};
const EditResourceDisplayName = "EditResource";
function EditResource({
  resourceId,
  uiResourceMeta: uiResourceMetaProp,
  resource: resourceFromProp,
  isNew: isNewProp,
  onDeleteComplete,
  onCancelClick,
  onSaveClick,
  onSaveComplete,
  onLoadComplete,
  onRefreshResource,
  relatedResourceId,
  relatedResourceName,
  onFormValidityChange,
  onPropertyUpdateComplete,
  onSavingStarting,
  onSavingEnding,
  config,
  defaultTab,
  ref
}) {
  const {
    globalConfig,
    setGlobalConfig
  } = useGlobalConfig();
  const resourceName = uiResourceMetaProp.resourceMeta.resourceName;
  const hasShowTabs = shouldShowTabs(uiResourceMetaProp);
  const [showHiddenProperties, setShowHiddenProperties] = useState(false);
  const [loadComplete, setLoadComplete] = useState(false);
  const [uiPropertyMetas, setUiPropertyMetas] = useState({});
  const rightUiPropertyMetas = {};
  const [customFields, setCustomFields] = useState([]);
  const [formFieldOptions, setFormFieldOptions] = useState({});
  const [formActiveSaveOperations, setFormActiveSaveOperations] = useState(0);
  const [formHasSavedOnce, setFormHasSavedOnce] = useState(false);
  const [multiListItems, setMultiListItems] = useState([]);
  const sourceEditResourceConfig = useEditResourceConfig(resourceName, config, hasShowTabs);
  const [editResourceConfig, setEditResourceConfig] = useState(sourceEditResourceConfig);
  const isFullLayout = editResourceConfig.tabsConfig?.layoutType === editResourceLayoutTypes.navigation;
  const initialIsNew = isNewProp ?? !isUuidSet(resourceId);
  const [isNew, setIsNew] = useState(initialIsNew);
  const [isLoadComplete, setIsLoadComplete] = useState(!isFullLayout);
  const [commentList, setCommentList] = useState([]);
  const [uiResourceMeta, setUiResourceMeta] = useState(uiResourceMetaProp);
  const {
    notifySaveComplete
  } = useSaveComplete();
  const [resource, setResource] = useState(() => getInitialEditResource(resourceFromProp, resourceId));
  const multiListConfig = getMultiListConfig(editResourceConfig.tableConfig, editResourceConfig.multiListSections);
  const editResourceId = useElementId(EditResource.displayName);
  const resourceRelations = useRef({});
  const readOnly = uiResourceMeta ? isReadOnlyResource(uiResourceMeta.resourceMeta) : true;
  const form = useForm({
    mode: formMethods.onChange
  });
  useEffect(() => {
    if (relatedResourceName && !form.getValues(relatedResourceName)) {
      form.setValue(relatedResourceName, relatedResourceId);
    }
  }, [form, relatedResourceId, relatedResourceName]);
  useEffect(() => {
    setResource(getInitialEditResource(resourceFromProp, resourceId));
  }, [resourceFromProp, resourceId]);
  useEffect(() => {
    onFormValidityChange?.(form.formState.isValid);
  }, [form.formState.isValid, onFormValidityChange]);
  useEffect(() => {
    setEditResourceConfig(prev => getSyncedEditResourceConfig(prev, sourceEditResourceConfig));
  }, [sourceEditResourceConfig]);
  const setResourceRelation = /* @__PURE__ */__name(relations => resourceRelations.current = relations, "setResourceRelation");
  useAsyncEffect(async () => {
    await onConfigChange(setIsNew, editResourceConfig, resource, setResource, setLoadComplete, uiPropertyMetas, setUiPropertyMetas, setFormFieldOptions, form.setValue, form.getValues, instanceNumber, uiResourceMeta, setResourceRelation, setCustomFields, initialIsNew, onLoadComplete, resourceFromProp);
  }, [config, editResourceConfig, isNewProp, resourceId, resourceFromProp]);
  const editResourceRef = useEditResourceRef(form, resource, isNew, uiResourceMeta, formHasSavedOnce, setFormActiveSaveOperations, setFormHasSavedOnce, setIsNew, notifySaveComplete, uiPropertyMetas, rightUiPropertyMetas, onSavingStarting, onSavingEnding, onSaveComplete, onSaveClick);
  useImperativeHandle(ref, () => editResourceRef, [editResourceRef]);
  useAsyncEffect(async () => {
    await initializeMultiListResources(resourceName, editResourceConfig, setMultiListItems, setEditResourceConfig, setResource, setUiResourceMeta, setIsLoadComplete, isNew, setCommentList, globalConfig, setGlobalConfig, resource.id);
  }, []);
  const resourceDisplayName = uiResourceMeta?.resourceMeta.display.displayName ?? "";
  let leftPanel;
  if (isFullLayout && !hasShowTabs) {
    leftPanel = /* @__PURE__ */jsx("div", {
      className: "border-input sticky max-h-full min-h-min shrink-0",
      children: /* @__PURE__ */jsx(Navigation, {
        open: true,
        config: {
          navigationItems: getEditNavigationItems(multiListItems, editResourceConfig?.multiListSections)
        }
      })
    });
  } else {
    leftPanel = /* @__PURE__ */jsx(FormProvider, {
      ...form,
      children: /* @__PURE__ */jsxs("div", {
        className: cn("flex w-full flex-col items-center gap-y-6"),
        children: [/* @__PURE__ */jsx(EditResourceHeader, {
          config: editResourceConfig,
          onCancel: async () => onCancelImageEdit(form, resource, onCancelClick),
          resourceDisplayName,
          resourceName,
          parentContextName: editResourceId,
          onToggleHiddenProperties: () => setShowHiddenProperties(!showHiddenProperties),
          showHiddenProperties,
          isNew,
          form,
          resourceMeta: uiResourceMeta.resourceMeta,
          shouldShowSaveCancelButtons: () => shouldShowSaveCancelButtons(isNew, uiResourceMeta),
          showDeleteButton: () => shouldEditResourceShowDeleteButton(isNew, uiResourceMeta.resourceMeta),
          onDeleteDialogResponse: async isYes => deleteResource(isYes, uiResourceMeta.resourceMeta.resourceName, resource, onDeleteComplete),
          onSaveResource: shouldCancel => onResourceSave(shouldCancel, () => onEditResourceValidation(uiResourceMeta, form, uiPropertyMetas, rightUiPropertyMetas), form, resource, isNew, uiResourceMeta.resourceMeta, setFormActiveSaveOperations, formHasSavedOnce, setFormHasSavedOnce, setIsNew, onSaveClick, onSaveComplete, notifySaveComplete, onSavingStarting, onSavingEnding),
          onChange: async (val, name) => onSaveResourceOnChange(val, name, formValues => onEditResourceValidation(uiResourceMeta, form, uiPropertyMetas, rightUiPropertyMetas, formValues), form, resource, isNew, uiResourceMeta.resourceMeta, setResource, resourceRelations.current, setResourceRelation, setFormActiveSaveOperations, editResourceConfig, onRefreshResource, notifySaveComplete, onSavingStarting, onSavingEnding, onPropertyUpdateComplete),
          saved: formActiveSaveOperations === 0,
          showSavingStatus: editResourceConfig.showSavingStatus,
          hasSavedOnce: formHasSavedOnce,
          backArrowUrl: editResourceConfig.backArrowUrl
        }), /* @__PURE__ */jsx(EditResourceFormBody, {
          resourceMeta: uiResourceMeta.resourceMeta,
          uiPropertyMetas,
          isNew,
          form,
          resource,
          formFieldOptions,
          parentContextName: editResourceId,
          config: editResourceConfig,
          showHiddenProperties,
          loadComplete,
          readOnly,
          onChangeSaveResource: async (val_0, name_0) => onSaveResourceOnChange(val_0, name_0, formValues_0 => onEditResourceValidation(uiResourceMeta, form, uiPropertyMetas, rightUiPropertyMetas, formValues_0), form, resource, isNew, uiResourceMeta.resourceMeta, setResource, resourceRelations.current, setResourceRelation, setFormActiveSaveOperations, editResourceConfig, onRefreshResource, notifySaveComplete, onSavingStarting, onSavingEnding, onPropertyUpdateComplete),
          customFields
        })]
      })
    });
  }
  if (!isFullLayout && !hasShowTabs) {
    return /* @__PURE__ */jsx("div", {
      id: editResourceId,
      children: leftPanel
    });
  }
  return /* @__PURE__ */jsx("div", {
    id: editResourceId,
    children: /* @__PURE__ */jsx(EditResourceTabs, {
      isLoadComplete,
      tabsHasSavedOnce: formHasSavedOnce,
      multiListItems,
      resourceName,
      resourceId: uiResourceMeta.resourceMeta.id,
      config: editResourceConfig,
      isNew,
      defaultTab,
      uiResourceMeta,
      multiListConfig,
      resource,
      commentList,
      children: leftPanel
    })
  });
}
__name(EditResource, "EditResource");
EditResource.displayName = EditResourceDisplayName;

export { EditResource, EditResourceDisplayName };
