"use client";
import { jsxs, jsx } from 'react/jsx-runtime';
import { useState, useRef, useEffect, useMemo } from 'react';
import { z } from 'zod';
import SteppedAutoForm from '../../../../../../../ui/src/components/auto-form/stepped-auto-form.mjs';
import { buildFieldConfigFromJsonSchema as buildFieldConfigFromJsonSchema$1 } from '../../../../../../../ui/src/components/auto-form/helpers.mjs';
import { formSchemaToZod } from '../../../../../../../ui/src/lib/schema-converter.mjs';
import { Input } from '../../../../../../../ui/src/components/input.mjs';
import { Label } from '../../../../../../../ui/src/components/label.mjs';
import { Badge } from '../../../../../../../ui/src/components/badge.mjs';
import { usePluginOverrides } from '@btst/stack/context';
import { slugify } from '../../../utils.mjs';
import { CMS_LOCALIZATION } from '../../localization/index.mjs';
import { CMSFileUpload } from './file-upload.mjs';
import { RelationField } from './relation-field.mjs';

function buildFieldConfigFromJsonSchema(jsonSchema, uploadImage, fieldComponents) {
  const baseConfig = buildFieldConfigFromJsonSchema$1(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__ */ jsxs("div", { className: "rounded-md border border-destructive bg-destructive/10 p-3 text-sm text-destructive", children: [
            "File upload requires an ",
            /* @__PURE__ */ jsx("code", { children: "uploadImage" }),
            " function in CMS overrides."
          ] })
        };
      } else {
        baseConfig[key] = {
          ...baseConfig[key],
          fieldType: (props) => /* @__PURE__ */ jsx(CMSFileUpload, { ...props, uploadImage })
        };
      }
    }
    if (prop.fieldType === "relation" && prop.relation && !fieldComponents?.["relation"]) {
      const relationConfig = prop.relation;
      baseConfig[key] = {
        ...baseConfig[key],
        fieldType: (props) => /* @__PURE__ */ jsx(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
  } = usePluginOverrides("cms");
  const localization = { ...CMS_LOCALIZATION, ...customLocalization };
  const [slug, setSlug] = useState(initialSlug);
  const [slugManuallyEdited, setSlugManuallyEdited] = useState(isEditing);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [formData, setFormData] = useState(initialData);
  const [slugError, setSlugError] = useState(null);
  const [submitError, setSubmitError] = useState(null);
  const hasSyncedPrefillRef = useRef(false);
  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]);
  useEffect(() => {
    if (isEditing && initialSlug) {
      setSlug(initialSlug);
    }
  }, [initialSlug, isEditing]);
  const jsonSchema = useMemo(() => {
    try {
      return JSON.parse(contentType.jsonSchema);
    } catch {
      return {};
    }
  }, [contentType.jsonSchema]);
  const zodSchema = useMemo(() => {
    try {
      return formSchemaToZod(jsonSchema);
    } catch {
      return z.object({});
    }
  }, [jsonSchema]);
  const fieldConfig = useMemo(
    () => buildFieldConfigFromJsonSchema(jsonSchema, uploadImage, fieldComponents),
    [jsonSchema, uploadImage, fieldComponents]
  );
  const slugSourceField = useMemo(
    () => findSlugSourceField(jsonSchema),
    [jsonSchema]
  );
  const handleValuesChange = (values) => {
    setFormData(values);
    if (!isEditing && !slugManuallyEdited && slugSourceField) {
      const sourceValue = values[slugSourceField];
      if (typeof sourceValue === "string" && sourceValue.trim()) {
        setSlug(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__ */ jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "slug", children: localization.CMS_LABEL_SLUG }),
        !isEditing && /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "text-xs", children: slugManuallyEdited ? localization.CMS_EDITOR_SLUG_MANUAL : localization.CMS_EDITOR_SLUG_AUTO })
      ] }),
      /* @__PURE__ */ jsx(
        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__ */ jsx("p", { className: "text-sm text-destructive", children: slugError }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: localization.CMS_LABEL_SLUG_DESCRIPTION })
    ] }),
    submitError && /* @__PURE__ */ jsx("div", { className: "rounded-md border border-destructive/50 bg-destructive/10 p-3", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: submitError }) }),
    /* @__PURE__ */ jsx(
      SteppedAutoForm,
      {
        formSchema: zodSchema,
        values: formData,
        onValuesChange: handleValuesChange,
        onSubmit: handleSubmit,
        fieldConfig,
        isSubmitting,
        submitButtonText: isSubmitting ? localization.CMS_STATUS_SAVING : localization.CMS_BUTTON_SAVE,
        children: onCancel && /* @__PURE__ */ jsx(
          "button",
          {
            type: "button",
            onClick: onCancel,
            className: "px-4 py-2 text-sm text-muted-foreground hover:text-foreground",
            children: localization.CMS_BUTTON_CANCEL
          }
        )
      }
    )
  ] });
}

export { ContentForm };
