"use client";
import { jsx, jsxs } from 'react/jsx-runtime';
import { useState, useEffect, useCallback } from 'react';
import { usePluginOverrides, useBasePath } from '@btst/stack/context';
import { Button } from '../../../../../../../ui/src/components/button.mjs';
import { Input } from '../../../../../../../ui/src/components/input.mjs';
import { Label } from '../../../../../../../ui/src/components/label.mjs';
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '../../../../../../../ui/src/components/select.mjs';
import { ArrowLeft, Save } from 'lucide-react';
import { toast } from 'sonner';
import { FormBuilder } from '../../../../../../../ui/src/components/form-builder/index.mjs';
import { useSuspenseFormById, useCreateForm, useUpdateForm } from '../../hooks/form-builder-hooks.mjs';
import { FORM_BUILDER_LOCALIZATION } from '../../localization/index.mjs';
import { slugify } from '../../../utils.mjs';

function FormBuilderPage({ id }) {
  if (id) {
    return /* @__PURE__ */ jsx(EditFormBuilderPage, { id });
  }
  return /* @__PURE__ */ jsx(CreateFormBuilderPage, {});
}
function EditFormBuilderPage({ id }) {
  const { form: existingForm } = useSuspenseFormById(id);
  return /* @__PURE__ */ jsx(FormBuilderPageContent, { id, existingForm });
}
function CreateFormBuilderPage() {
  return /* @__PURE__ */ jsx(FormBuilderPageContent, {});
}
function FormBuilderPageContent({
  id,
  existingForm
}) {
  const { navigate, Link, localization } = usePluginOverrides("form-builder", {
    localization: FORM_BUILDER_LOCALIZATION
  });
  const basePath = useBasePath();
  const createMutation = useCreateForm();
  const updateMutation = useUpdateForm();
  const loc = localization || FORM_BUILDER_LOCALIZATION;
  const LinkComponent = Link || "a";
  const [name, setName] = useState(existingForm?.name || "");
  const [slug, setSlug] = useState(existingForm?.slug || "");
  const [status, setStatus] = useState(
    existingForm?.status || "active"
  );
  const [schema, setSchema] = useState(() => {
    if (existingForm?.schema) {
      try {
        return JSON.parse(existingForm.schema);
      } catch {
        return void 0;
      }
    }
    return void 0;
  });
  const [autoSlug, setAutoSlug] = useState(!id);
  useEffect(() => {
    if (autoSlug && name) {
      setSlug(slugify(name));
    }
  }, [name, autoSlug]);
  const handleSchemaChange = useCallback((newSchema) => {
    setSchema(newSchema);
  }, []);
  const handleSave = async () => {
    if (!name.trim()) {
      toast.error("Name is required");
      return;
    }
    if (!slug.trim()) {
      toast.error("Slug is required");
      return;
    }
    if (!schema) {
      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
          }
        });
        toast.success(loc.FORM_BUILDER_TOAST_UPDATE_SUCCESS);
      } else {
        const newForm = await createMutation.mutateAsync({
          name,
          slug,
          schema: schemaStr,
          status
        });
        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")) {
        toast.error(loc.FORM_BUILDER_TOAST_DUPLICATE_SLUG);
      } else {
        toast.error(loc.FORM_BUILDER_TOAST_ERROR);
      }
    }
  };
  const isSaving = createMutation.isPending || updateMutation.isPending;
  return /* @__PURE__ */ jsxs("div", { className: "flex h-full flex-col", "data-testid": "form-builder-page", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4 border-b p-4", children: [
      /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "icon", asChild: true, children: /* @__PURE__ */ jsx(LinkComponent, { href: `${basePath}/forms`, children: /* @__PURE__ */ jsx(ArrowLeft, { className: "h-4 w-4" }) }) }),
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "form-name", className: "text-xs text-muted-foreground", children: loc.FORM_BUILDER_LABEL_NAME }),
        /* @__PURE__ */ jsx(
          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__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "form-slug", className: "text-xs text-muted-foreground", children: loc.FORM_BUILDER_LABEL_SLUG }),
        /* @__PURE__ */ jsx(
          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__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
        /* @__PURE__ */ jsx(
          Label,
          {
            htmlFor: "form-status",
            className: "text-xs text-muted-foreground",
            children: loc.FORM_BUILDER_LABEL_STATUS
          }
        ),
        /* @__PURE__ */ jsxs(
          Select,
          {
            value: status,
            onValueChange: (v) => setStatus(v),
            children: [
              /* @__PURE__ */ jsx(SelectTrigger, { className: "h-8 w-28", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
              /* @__PURE__ */ jsxs(SelectContent, { children: [
                /* @__PURE__ */ jsx(SelectItem, { value: "active", children: loc.FORM_BUILDER_STATUS_ACTIVE }),
                /* @__PURE__ */ jsx(SelectItem, { value: "inactive", children: loc.FORM_BUILDER_STATUS_INACTIVE }),
                /* @__PURE__ */ jsx(SelectItem, { value: "archived", children: loc.FORM_BUILDER_STATUS_ARCHIVED })
              ] })
            ]
          }
        )
      ] }),
      /* @__PURE__ */ jsx("div", { className: "ml-auto", children: /* @__PURE__ */ jsxs(Button, { onClick: handleSave, disabled: isSaving, children: [
        /* @__PURE__ */ jsx(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__ */ jsx(
      FormBuilder,
      {
        value: schema,
        onChange: handleSchemaChange,
        className: "flex-1"
      }
    )
  ] });
}

export { FormBuilderPage };
