"use client";
'use strict';

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');
const context = require('@btst/stack/context');
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 skeleton = require('../../../../../../../ui/src/components/skeleton.cjs');
const LucideIcons = require('lucide-react');
const formBuilderHooks = require('../../hooks/form-builder-hooks.cjs');
const index = require('../../localization/index.cjs');

function DefaultLoadingComponent() {
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsxRuntime.jsx(skeleton.Skeleton, { className: "h-10 w-full" }),
    /* @__PURE__ */ jsxRuntime.jsx(skeleton.Skeleton, { className: "h-10 w-full" }),
    /* @__PURE__ */ jsxRuntime.jsx(skeleton.Skeleton, { className: "h-10 w-full" }),
    /* @__PURE__ */ jsxRuntime.jsx(skeleton.Skeleton, { className: "h-10 w-32" })
  ] });
}
function DefaultErrorComponent({ error }) {
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col items-center justify-center py-8 text-center", children: [
    /* @__PURE__ */ jsxRuntime.jsx("div", { className: "rounded-full bg-destructive/10 p-3 mb-4", children: /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.AlertCircle, { className: "h-6 w-6 text-destructive" }) }),
    /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-lg font-medium text-foreground mb-2", children: "Failed to load form" }),
    /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground max-w-sm", children: error.message || "An unexpected error occurred" })
  ] });
}
function DefaultSuccessComponent({ message }) {
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col items-center justify-center py-8 text-center", children: [
    /* @__PURE__ */ jsxRuntime.jsx("div", { className: "rounded-full bg-green-100 dark:bg-green-900 p-3 mb-4", children: /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.CheckCircle, { className: "h-6 w-6 text-green-600 dark:text-green-400" }) }),
    /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-lg font-medium text-foreground mb-2", children: "Form Submitted" }),
    /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground max-w-sm", children: message })
  ] });
}
function FormRenderer({
  slug,
  onSuccess,
  onError,
  fieldComponents: propFieldComponents,
  successMessage: propSuccessMessage,
  submitButtonText,
  LoadingComponent = DefaultLoadingComponent,
  ErrorComponent = DefaultErrorComponent,
  className
}) {
  const { fieldComponents: overrideFieldComponents, localization } = context.usePluginOverrides("form-builder", {
    localization: index.FORM_BUILDER_LOCALIZATION
  });
  const loc = localization || index.FORM_BUILDER_LOCALIZATION;
  const { form, isLoading, error } = formBuilderHooks.useFormBySlug(slug);
  const submitMutation = formBuilderHooks.useSubmitForm(slug);
  const [submitted, setSubmitted] = React.useState(false);
  const [finalSuccessMessage, setFinalSuccessMessage] = React.useState(
    null
  );
  const mergedFieldComponents = React.useMemo(
    () => ({
      ...overrideFieldComponents,
      ...propFieldComponents
    }),
    [overrideFieldComponents, propFieldComponents]
  );
  const { zodSchema, fieldConfig } = React.useMemo(() => {
    if (!form?.schema) {
      return { zodSchema: null, fieldConfig: {} };
    }
    try {
      const parsedSchema = JSON.parse(form.schema);
      const zod = schemaConverter.formSchemaToZod(parsedSchema);
      const config = helpers.buildFieldConfigFromJsonSchema(
        parsedSchema,
        mergedFieldComponents
      );
      return { zodSchema: zod, fieldConfig: config };
    } catch {
      return { zodSchema: null, fieldConfig: {} };
    }
  }, [form?.schema, mergedFieldComponents]);
  const handleSubmit = async (data) => {
    try {
      const result = await submitMutation.mutateAsync({ data });
      const message = propSuccessMessage || result.form.successMessage || "Thank you for your submission!";
      setFinalSuccessMessage(message);
      setSubmitted(true);
      onSuccess?.(result);
      if (result.form.redirectUrl) {
        window.location.href = result.form.redirectUrl;
        return;
      }
    } catch (err) {
      onError?.(err);
    }
  };
  if (isLoading) {
    return /* @__PURE__ */ jsxRuntime.jsx("div", { className, children: /* @__PURE__ */ jsxRuntime.jsx(LoadingComponent, {}) });
  }
  if (error) {
    return /* @__PURE__ */ jsxRuntime.jsx("div", { className, children: /* @__PURE__ */ jsxRuntime.jsx(ErrorComponent, { error }) });
  }
  if (!form) {
    return /* @__PURE__ */ jsxRuntime.jsx("div", { className, children: /* @__PURE__ */ jsxRuntime.jsx(ErrorComponent, { error: new Error("Form not found") }) });
  }
  if (form.status !== "active") {
    return /* @__PURE__ */ jsxRuntime.jsx("div", { className, children: /* @__PURE__ */ jsxRuntime.jsx(
      ErrorComponent,
      {
        error: new Error("This form is not currently accepting submissions")
      }
    ) });
  }
  if (!zodSchema) {
    return /* @__PURE__ */ jsxRuntime.jsx("div", { className, children: /* @__PURE__ */ jsxRuntime.jsx(ErrorComponent, { error: new Error("Failed to parse form schema") }) });
  }
  if (submitted && finalSuccessMessage) {
    return /* @__PURE__ */ jsxRuntime.jsx("div", { className, children: /* @__PURE__ */ jsxRuntime.jsx(DefaultSuccessComponent, { message: finalSuccessMessage }) });
  }
  return /* @__PURE__ */ jsxRuntime.jsx("div", { className, "data-testid": "form-renderer", children: /* @__PURE__ */ jsxRuntime.jsx(
    steppedAutoForm.default,
    {
      formSchema: zodSchema,
      fieldConfig,
      onSubmit: (values) => handleSubmit(values),
      isSubmitting: submitMutation.isPending,
      submitButtonText: submitButtonText || loc.FORM_BUILDER_BUTTON_SUBMIT
    }
  ) });
}

exports.FormRenderer = FormRenderer;
