"use client";
'use strict';

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');
const z = require('zod');
const steppedAutoForm = require('../../../../../../../ui/src/components/auto-form/stepped-auto-form.cjs');
const helpers = require('../../../../../../../ui/src/components/auto-form/helpers.cjs');
const schemaConverter = require('../../../../../../../ui/src/lib/schema-converter.cjs');
const input = require('../../../../../../../ui/src/components/input.cjs');
const label = require('../../../../../../../ui/src/components/label.cjs');
const badge = require('../../../../../../../ui/src/components/badge.cjs');
const context = require('@btst/stack/context');
const utils = require('../../../utils.cjs');
const index = require('../../localization/index.cjs');
const fileUpload = require('./file-upload.cjs');
const relationField = require('./relation-field.cjs');

function buildFieldConfigFromJsonSchema(jsonSchema, uploadImage, fieldComponents) {
  const baseConfig = helpers.buildFieldConfigFromJsonSchema(jsonSchema, fieldComponents);
  const properties = jsonSchema.properties;
  if (!properties) return baseConfig;
  for (const [key, prop] of Object.entries(properties)) {
    if (prop.fieldType === "file" && !fieldComponents?.["file"]) {
      if (!uploadImage) {
        baseConfig[key] = {
          ...baseConfig[key],
          fieldType: () => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "rounded-md border border-destructive bg-destructive/10 p-3 text-sm text-destructive", children: [
            "File upload requires an ",
            /* @__PURE__ */ jsxRuntime.jsx("code", { children: "uploadImage" }),
            " function in CMS overrides."
          ] })
        };
      } else {
        baseConfig[key] = {
          ...baseConfig[key],
          fieldType: (props) => /* @__PURE__ */ jsxRuntime.jsx(fileUpload.CMSFileUpload, { ...props, uploadImage })
        };
      }
    }
    if (prop.fieldType === "relation" && prop.relation && !fieldComponents?.["relation"]) {
      const relationConfig = prop.relation;
      baseConfig[key] = {
        ...baseConfig[key],
        fieldType: (props) => /* @__PURE__ */ jsxRuntime.jsx(relationField.RelationField, { ...props, relation: relationConfig })
      };
    }
  }
  return baseConfig;
}
function findSlugSourceField(jsonSchema) {
  const properties = jsonSchema.properties;
  if (!properties) return null;
  const priorityFields = ["name", "title", "heading", "label"];
  for (const field of priorityFields) {
    if (properties[field]?.type === "string") {
      return field;
    }
  }
  for (const [key, value] of Object.entries(properties)) {
    if (value.type === "string") {
      return key;
    }
  }
  return null;
}
function ContentForm({
  contentType,
  initialData = {},
  initialSlug = "",
  isEditing = false,
  onSubmit,
  onCancel
}) {
  const {
    localization: customLocalization,
    uploadImage,
    fieldComponents
  } = context.usePluginOverrides("cms");
  const localization = { ...index.CMS_LOCALIZATION, ...customLocalization };
  const [slug, setSlug] = React.useState(initialSlug);
  const [slugManuallyEdited, setSlugManuallyEdited] = React.useState(isEditing);
  const [isSubmitting, setIsSubmitting] = React.useState(false);
  const [formData, setFormData] = React.useState(initialData);
  const [slugError, setSlugError] = React.useState(null);
  const [submitError, setSubmitError] = React.useState(null);
  const hasSyncedPrefillRef = React.useRef(false);
  React.useEffect(() => {
    const hasData = Object.keys(initialData).length > 0;
    const shouldSync = hasData && (isEditing || !hasSyncedPrefillRef.current);
    if (shouldSync) {
      setFormData(initialData);
      if (!isEditing) {
        hasSyncedPrefillRef.current = true;
      }
    }
  }, [initialData, isEditing]);
  React.useEffect(() => {
    if (isEditing && initialSlug) {
      setSlug(initialSlug);
    }
  }, [initialSlug, isEditing]);
  const jsonSchema = React.useMemo(() => {
    try {
      return JSON.parse(contentType.jsonSchema);
    } catch {
      return {};
    }
  }, [contentType.jsonSchema]);
  const zodSchema = React.useMemo(() => {
    try {
      return schemaConverter.formSchemaToZod(jsonSchema);
    } catch {
      return z.z.object({});
    }
  }, [jsonSchema]);
  const fieldConfig = React.useMemo(
    () => buildFieldConfigFromJsonSchema(jsonSchema, uploadImage, fieldComponents),
    [jsonSchema, uploadImage, fieldComponents]
  );
  const slugSourceField = React.useMemo(
    () => findSlugSourceField(jsonSchema),
    [jsonSchema]
  );
  const handleValuesChange = (values) => {
    setFormData(values);
    if (!isEditing && !slugManuallyEdited && slugSourceField) {
      const sourceValue = values[slugSourceField];
      if (typeof sourceValue === "string" && sourceValue.trim()) {
        setSlug(utils.slugify(sourceValue));
      }
    }
  };
  const handleSubmit = async (data) => {
    setSlugError(null);
    setSubmitError(null);
    if (!slug.trim()) {
      setSlugError("Slug is required");
      return;
    }
    setIsSubmitting(true);
    try {
      await onSubmit({ slug, data });
    } catch (error) {
      const message = error instanceof Error ? error.message : localization.CMS_TOAST_ERROR;
      setSubmitError(message);
    } finally {
      setIsSubmitting(false);
    }
  };
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntime.jsx(label.Label, { htmlFor: "slug", children: localization.CMS_LABEL_SLUG }),
        !isEditing && /* @__PURE__ */ jsxRuntime.jsx(badge.Badge, { variant: "outline", className: "text-xs", children: slugManuallyEdited ? localization.CMS_EDITOR_SLUG_MANUAL : localization.CMS_EDITOR_SLUG_AUTO })
      ] }),
      /* @__PURE__ */ jsxRuntime.jsx(
        input.Input,
        {
          id: "slug",
          value: slug,
          onChange: (e) => {
            setSlug(e.target.value);
            setSlugError(null);
            if (!isEditing) {
              setSlugManuallyEdited(true);
            }
          },
          disabled: isEditing,
          placeholder: slugSourceField ? `Auto-generated from ${slugSourceField}` : "Enter slug..."
        }
      ),
      slugError && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-destructive", children: slugError }),
      /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: localization.CMS_LABEL_SLUG_DESCRIPTION })
    ] }),
    submitError && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "rounded-md border border-destructive/50 bg-destructive/10 p-3", children: /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-destructive", children: submitError }) }),
    /* @__PURE__ */ jsxRuntime.jsx(
      steppedAutoForm.default,
      {
        formSchema: zodSchema,
        values: formData,
        onValuesChange: handleValuesChange,
        onSubmit: handleSubmit,
        fieldConfig,
        isSubmitting,
        submitButtonText: isSubmitting ? localization.CMS_STATUS_SAVING : localization.CMS_BUTTON_SAVE,
        children: onCancel && /* @__PURE__ */ jsxRuntime.jsx(
          "button",
          {
            type: "button",
            onClick: onCancel,
            className: "px-4 py-2 text-sm text-muted-foreground hover:text-foreground",
            children: localization.CMS_BUTTON_CANCEL
          }
        )
      }
    )
  ] });
}

exports.ContentForm = ContentForm;
