'use strict';

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');
const z = require('zod');
const layerStore = require('../../../lib/ui-builder/store/layer-store.cjs');
const editorStore = require('../../../lib/ui-builder/store/editor-store.cjs');
const button = require('../../button.cjs');
const index = require('../../auto-form/index.cjs');
const editorUtils = require('../../../lib/ui-builder/store/editor-utils.cjs');
const schemaUtils = require('../../../lib/ui-builder/store/schema-utils.cjs');
const helpers = require('../../auto-form/helpers.cjs');
const variableResolver = require('../../../lib/ui-builder/utils/variable-resolver.cjs');
const types = require('../types.cjs');

function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }

const React__default = /*#__PURE__*/_interopDefaultCompat(React);

const PropsPanel = React__default.memo(({ className }) => {
  const selectedLayerId = layerStore.useLayerStore((state) => state.selectedLayerId);
  const findLayerById = layerStore.useLayerStore((state) => state.findLayerById);
  const removeLayer = layerStore.useLayerStore((state) => state.removeLayer);
  const duplicateLayer = layerStore.useLayerStore((state) => state.duplicateLayer);
  const updateLayer = layerStore.useLayerStore((state) => state.updateLayer);
  const addComponentLayer = layerStore.useLayerStore((state) => state.addComponentLayer);
  const componentRegistry = editorStore.useEditorStore((state) => state.registry);
  const selectedLayer = findLayerById(selectedLayerId);
  const handleAddComponentLayer = React.useCallback(
    (layerType, parentLayerId, addPosition) => {
      addComponentLayer(layerType, parentLayerId, addPosition);
    },
    [addComponentLayer]
  );
  const handleDeleteLayer = React.useCallback(
    (layerId) => {
      removeLayer(layerId);
    },
    [removeLayer]
  );
  const handleDuplicateLayer = React.useCallback(() => {
    if (selectedLayer) {
      duplicateLayer(selectedLayer.id);
    }
  }, [selectedLayer, duplicateLayer]);
  const handleUpdateLayer = React.useCallback(
    (id, props, rest) => {
      updateLayer(id, props, rest);
    },
    [updateLayer]
  );
  if (selectedLayer && !componentRegistry[selectedLayer.type]) {
    return null;
  }
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className, children: [
    selectedLayer && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
      /* @__PURE__ */ jsxRuntime.jsx(Title, {}),
      /* @__PURE__ */ jsxRuntime.jsxs("h3", { className: "text-base font-medium mb-4", children: [
        "Type: ",
        selectedLayer.type.replaceAll("_", "")
      ] })
    ] }),
    !selectedLayer && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
      /* @__PURE__ */ jsxRuntime.jsx("h2", { className: "text-xl font-semibold mb-2", children: "Component Properties" }),
      /* @__PURE__ */ jsxRuntime.jsx("p", { children: "No component selected" })
    ] }),
    selectedLayer && /* @__PURE__ */ jsxRuntime.jsx(
      ComponentPropsAutoForm,
      {
        componentRegistry,
        selectedLayerId: selectedLayer.id,
        removeLayer: handleDeleteLayer,
        duplicateLayer: handleDuplicateLayer,
        updateLayer: handleUpdateLayer,
        addComponentLayer: handleAddComponentLayer
      },
      selectedLayer.id
    )
  ] });
});
PropsPanel.displayName = "PropsPanel";
const EMPTY_ZOD_SCHEMA = z.z.object({});
const EMPTY_FORM_VALUES = {};
const ComponentPropsAutoForm = ({
  selectedLayerId,
  componentRegistry,
  removeLayer,
  duplicateLayer,
  updateLayer,
  addComponentLayer
}) => {
  const findLayerById = layerStore.useLayerStore((state) => state.findLayerById);
  const revisionCounter = editorStore.useEditorStore((state) => state.revisionCounter);
  const selectedLayer = findLayerById(selectedLayerId);
  const isPage = layerStore.useLayerStore((state) => state.isLayerAPage(selectedLayerId));
  const allowPagesCreation = editorStore.useEditorStore(
    (state) => state.allowPagesCreation
  );
  const allowPagesDeletion = editorStore.useEditorStore(
    (state) => state.allowPagesDeletion
  );
  const { schema } = React.useMemo(() => {
    if (selectedLayer && componentRegistry[selectedLayer.type]) {
      const registryEntry = componentRegistry[selectedLayer.type];
      if (registryEntry) {
        return registryEntry;
      }
    }
    return { schema: EMPTY_ZOD_SCHEMA };
  }, [selectedLayer, componentRegistry]);
  const handleDeleteLayer = React.useCallback(() => {
    removeLayer(selectedLayerId);
  }, [removeLayer, selectedLayerId]);
  const handleDuplicateLayer = React.useCallback(() => {
    duplicateLayer(selectedLayerId);
  }, [duplicateLayer, selectedLayerId]);
  const variables = layerStore.useLayerStore((state) => state.variables);
  const onParsedValuesChange = React.useCallback(
    (parsedValues) => {
      const { children, ...dataProps } = parsedValues;
      const preservedProps = {};
      if (selectedLayer) {
        Object.assign(preservedProps, selectedLayer.props);
        Object.keys(dataProps).forEach((key) => {
          const originalValue = selectedLayer.props[key];
          const newValue = dataProps[key];
          const fieldDef = "shape" in schema && schema.shape ? schema.shape[key] : void 0;
          const baseType = fieldDef ? helpers.getBaseType(fieldDef) : void 0;
          if (types.isVariableReference(originalValue)) {
            const variableExists = variables.some((v) => v.id === originalValue.__variableRef);
            if (variableExists) {
              preservedProps[key] = originalValue;
            } else {
              preservedProps[key] = newValue;
            }
          } else {
            if (baseType === "ZodDate" && newValue instanceof Date) {
              preservedProps[key] = newValue.toISOString();
            } else {
              preservedProps[key] = newValue;
            }
          }
        });
      }
      const originalChildren = selectedLayer?.children;
      const shouldPreserveChildrenBinding = types.isVariableReference(originalChildren) && variables.some((v) => v.id === originalChildren.__variableRef);
      if (shouldPreserveChildrenBinding) {
        updateLayer(selectedLayerId, preservedProps);
      } else if (typeof children === "string") {
        updateLayer(selectedLayerId, preservedProps, { children });
      } else if (children && children.layerType) {
        updateLayer(selectedLayerId, preservedProps, {
          children: selectedLayer?.children
        });
        addComponentLayer(
          children.layerType,
          selectedLayerId,
          children.addPosition
        );
      } else {
        updateLayer(selectedLayerId, preservedProps);
      }
    },
    [updateLayer, selectedLayerId, selectedLayer, addComponentLayer, schema, variables]
  );
  const formValues = React.useMemo(() => {
    if (!selectedLayer) return EMPTY_FORM_VALUES;
    const resolvedProps = variableResolver.resolveVariableReferences(
      selectedLayer.props,
      variables
    );
    const transformedProps = {};
    const schemaShape = "shape" in schema && schema.shape ? schema.shape : void 0;
    if (schemaShape) {
      for (const [key, value] of Object.entries(resolvedProps)) {
        const fieldDef = schemaShape[key];
        if (fieldDef) {
          const baseType = helpers.getBaseType(fieldDef);
          if (baseType === "ZodEnum") {
            transformedProps[key] = typeof value === "string" ? value : String(value);
          } else if (baseType === "ZodDate") {
            if (value instanceof Date) {
              transformedProps[key] = value;
            } else if (typeof value === "string" || typeof value === "number") {
              const date = new Date(value);
              transformedProps[key] = isNaN(date.getTime()) ? void 0 : date;
            } else {
              transformedProps[key] = void 0;
            }
          } else {
            transformedProps[key] = value;
          }
        } else {
          transformedProps[key] = value;
        }
      }
    } else {
      Object.assign(transformedProps, resolvedProps);
    }
    return { ...transformedProps, children: selectedLayer.children };
  }, [selectedLayer, schema, revisionCounter]);
  const autoFormSchema = React.useMemo(() => {
    if ("shape" in schema && typeof schema.shape === "object") {
      try {
        return schemaUtils.addDefaultValues(schema, formValues);
      } catch (error) {
        console.warn("Failed to add default values to schema:", error);
        return schema;
      }
    }
    return schema;
  }, [schema, formValues]);
  const autoFormFieldConfig = React.useMemo(() => {
    if (!selectedLayer) return void 0;
    return editorUtils.generateFieldOverrides(componentRegistry, selectedLayer);
  }, [componentRegistry, selectedLayer, selectedLayer?.props]);
  const formKey = React.useMemo(() => {
    return `${selectedLayerId}-${revisionCounter}`;
  }, [selectedLayerId, revisionCounter]);
  if (!selectedLayer || !componentRegistry[selectedLayer.type]) {
    return null;
  }
  return /* @__PURE__ */ jsxRuntime.jsxs(
    index.default,
    {
      formSchema: autoFormSchema,
      values: formValues,
      onParsedValuesChange,
      fieldConfig: autoFormFieldConfig,
      className: "space-y-4 mt-4",
      children: [
        (!isPage || allowPagesCreation) && /* @__PURE__ */ jsxRuntime.jsxs(
          button.Button,
          {
            type: "button",
            variant: "secondary",
            className: "mt-4 w-full",
            onClick: handleDuplicateLayer,
            "data-testid": `button-Duplicate ,${isPage ? "Page" : "Component"}`,
            children: [
              "Duplicate ",
              isPage ? "Page" : "Component"
            ]
          }
        ),
        (!isPage || allowPagesDeletion) && /* @__PURE__ */ jsxRuntime.jsxs(
          button.Button,
          {
            type: "button",
            variant: "destructive",
            className: "mt-4 w-full",
            onClick: handleDeleteLayer,
            "data-testid": `button-Delete ,${isPage ? "Page" : "Component"}`,
            children: [
              "Delete ",
              isPage ? "Page" : "Component"
            ]
          }
        )
      ]
    },
    formKey
  );
};
ComponentPropsAutoForm.displayName = "ComponentPropsAutoForm";
const nameForLayer = (layer) => {
  return layer.name || layer.type.replaceAll("_", "");
};
const Title = React__default.memo(() => {
  const selectedLayer = layerStore.useLayerStore((state) => {
    const selectedLayerId = state.selectedLayerId;
    return selectedLayerId ? state.findLayerById(selectedLayerId) : null;
  });
  return /* @__PURE__ */ jsxRuntime.jsxs("h2", { className: "text-xl font-semibold mb-2", children: [
    selectedLayer ? nameForLayer(selectedLayer) : "",
    " Properties"
  ] });
});
Title.displayName = "Title";

module.exports = PropsPanel;
