"use client";
'use strict';

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');
const context = require('@btst/stack/context');
const button = require('../../../../../../../ui/src/components/button.cjs');
const input = require('../../../../../../../ui/src/components/input.cjs');
const label = require('../../../../../../../ui/src/components/label.cjs');
const select = require('../../../../../../../ui/src/components/select.cjs');
const LucideIcons = require('lucide-react');
const sonner = require('sonner');
const index$1 = require('../../../../../../../ui/src/components/form-builder/index.cjs');
const formBuilderHooks = require('../../hooks/form-builder-hooks.cjs');
const index = require('../../localization/index.cjs');
const utils = require('../../../utils.cjs');

function FormBuilderPage({ id }) {
  if (id) {
    return /* @__PURE__ */ jsxRuntime.jsx(EditFormBuilderPage, { id });
  }
  return /* @__PURE__ */ jsxRuntime.jsx(CreateFormBuilderPage, {});
}
function EditFormBuilderPage({ id }) {
  const { form: existingForm } = formBuilderHooks.useSuspenseFormById(id);
  return /* @__PURE__ */ jsxRuntime.jsx(FormBuilderPageContent, { id, existingForm });
}
function CreateFormBuilderPage() {
  return /* @__PURE__ */ jsxRuntime.jsx(FormBuilderPageContent, {});
}
function FormBuilderPageContent({
  id,
  existingForm
}) {
  const { navigate, Link, localization } = context.usePluginOverrides("form-builder", {
    localization: index.FORM_BUILDER_LOCALIZATION
  });
  const basePath = context.useBasePath();
  const createMutation = formBuilderHooks.useCreateForm();
  const updateMutation = formBuilderHooks.useUpdateForm();
  const loc = localization || index.FORM_BUILDER_LOCALIZATION;
  const LinkComponent = Link || "a";
  const [name, setName] = React.useState(existingForm?.name || "");
  const [slug, setSlug] = React.useState(existingForm?.slug || "");
  const [status, setStatus] = React.useState(
    existingForm?.status || "active"
  );
  const [schema, setSchema] = React.useState(() => {
    if (existingForm?.schema) {
      try {
        return JSON.parse(existingForm.schema);
      } catch {
        return void 0;
      }
    }
    return void 0;
  });
  const [autoSlug, setAutoSlug] = React.useState(!id);
  React.useEffect(() => {
    if (autoSlug && name) {
      setSlug(utils.slugify(name));
    }
  }, [name, autoSlug]);
  const handleSchemaChange = React.useCallback((newSchema) => {
    setSchema(newSchema);
  }, []);
  const handleSave = async () => {
    if (!name.trim()) {
      sonner.toast.error("Name is required");
      return;
    }
    if (!slug.trim()) {
      sonner.toast.error("Slug is required");
      return;
    }
    if (!schema) {
      sonner.toast.error("Please add at least one field to the form");
      return;
    }
    try {
      const schemaStr = JSON.stringify(schema);
      if (id) {
        await updateMutation.mutateAsync({
          id,
          data: {
            name,
            schema: schemaStr,
            status
          }
        });
        sonner.toast.success(loc.FORM_BUILDER_TOAST_UPDATE_SUCCESS);
      } else {
        const newForm = await createMutation.mutateAsync({
          name,
          slug,
          schema: schemaStr,
          status
        });
        sonner.toast.success(loc.FORM_BUILDER_TOAST_CREATE_SUCCESS);
        navigate?.(`${basePath}/forms/${newForm.id}/edit`);
      }
    } catch (error) {
      const message = error instanceof Error ? error.message : "Unknown error";
      if (message.includes("slug already exists")) {
        sonner.toast.error(loc.FORM_BUILDER_TOAST_DUPLICATE_SLUG);
      } else {
        sonner.toast.error(loc.FORM_BUILDER_TOAST_ERROR);
      }
    }
  };
  const isSaving = createMutation.isPending || updateMutation.isPending;
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex h-full flex-col", "data-testid": "form-builder-page", children: [
    /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-4 border-b p-4", children: [
      /* @__PURE__ */ jsxRuntime.jsx(button.Button, { variant: "ghost", size: "icon", asChild: true, children: /* @__PURE__ */ jsxRuntime.jsx(LinkComponent, { href: `${basePath}/forms`, children: /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.ArrowLeft, { className: "h-4 w-4" }) }) }),
      /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col gap-1", children: [
        /* @__PURE__ */ jsxRuntime.jsx(label.Label, { htmlFor: "form-name", className: "text-xs text-muted-foreground", children: loc.FORM_BUILDER_LABEL_NAME }),
        /* @__PURE__ */ jsxRuntime.jsx(
          input.Input,
          {
            id: "form-name",
            value: name,
            onChange: (e) => setName(e.target.value),
            placeholder: loc.FORM_BUILDER_EDITOR_NAME_PLACEHOLDER,
            className: "h-8 w-48"
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col gap-1", children: [
        /* @__PURE__ */ jsxRuntime.jsx(label.Label, { htmlFor: "form-slug", className: "text-xs text-muted-foreground", children: loc.FORM_BUILDER_LABEL_SLUG }),
        /* @__PURE__ */ jsxRuntime.jsx(
          input.Input,
          {
            id: "form-slug",
            value: slug,
            onChange: (e) => {
              setSlug(e.target.value);
              setAutoSlug(false);
            },
            placeholder: loc.FORM_BUILDER_EDITOR_SLUG_PLACEHOLDER,
            className: "h-8 w-48 font-mono text-sm",
            disabled: !!id
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col gap-1", children: [
        /* @__PURE__ */ jsxRuntime.jsx(
          label.Label,
          {
            htmlFor: "form-status",
            className: "text-xs text-muted-foreground",
            children: loc.FORM_BUILDER_LABEL_STATUS
          }
        ),
        /* @__PURE__ */ jsxRuntime.jsxs(
          select.Select,
          {
            value: status,
            onValueChange: (v) => setStatus(v),
            children: [
              /* @__PURE__ */ jsxRuntime.jsx(select.SelectTrigger, { className: "h-8 w-28", children: /* @__PURE__ */ jsxRuntime.jsx(select.SelectValue, {}) }),
              /* @__PURE__ */ jsxRuntime.jsxs(select.SelectContent, { children: [
                /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: "active", children: loc.FORM_BUILDER_STATUS_ACTIVE }),
                /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: "inactive", children: loc.FORM_BUILDER_STATUS_INACTIVE }),
                /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: "archived", children: loc.FORM_BUILDER_STATUS_ARCHIVED })
              ] })
            ]
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntime.jsx("div", { className: "ml-auto", children: /* @__PURE__ */ jsxRuntime.jsxs(button.Button, { onClick: handleSave, disabled: isSaving, children: [
        /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Save, { className: "mr-2 h-4 w-4" }),
        isSaving ? loc.FORM_BUILDER_STATUS_SAVING : id ? loc.FORM_BUILDER_BUTTON_SAVE : loc.FORM_BUILDER_BUTTON_CREATE
      ] }) })
    ] }),
    /* @__PURE__ */ jsxRuntime.jsx(
      index$1.FormBuilder,
      {
        value: schema,
        onChange: handleSchemaChange,
        className: "flex-1"
      }
    )
  ] });
}

exports.FormBuilderPage = FormBuilderPage;
