"use client";
import { jsx, jsxs } from 'react/jsx-runtime';
import { useState, useMemo } from 'react';
import { usePluginOverrides } from '@btst/stack/context';
import SteppedAutoForm from '../../../../../../../ui/src/components/auto-form/stepped-auto-form.mjs';
import { buildFieldConfigFromJsonSchema } from '../../../../../../../ui/src/components/auto-form/helpers.mjs';
import { formSchemaToZod } from '../../../../../../../ui/src/lib/schema-converter.mjs';
import { Skeleton } from '../../../../../../../ui/src/components/skeleton.mjs';
import { AlertCircle, CheckCircle } from 'lucide-react';
import { useFormBySlug, useSubmitForm } from '../../hooks/form-builder-hooks.mjs';
import { FORM_BUILDER_LOCALIZATION } from '../../localization/index.mjs';

function DefaultLoadingComponent() {
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsx(Skeleton, { className: "h-10 w-full" }),
    /* @__PURE__ */ jsx(Skeleton, { className: "h-10 w-full" }),
    /* @__PURE__ */ jsx(Skeleton, { className: "h-10 w-full" }),
    /* @__PURE__ */ jsx(Skeleton, { className: "h-10 w-32" })
  ] });
}
function DefaultErrorComponent({ error }) {
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center py-8 text-center", children: [
    /* @__PURE__ */ jsx("div", { className: "rounded-full bg-destructive/10 p-3 mb-4", children: /* @__PURE__ */ jsx(AlertCircle, { className: "h-6 w-6 text-destructive" }) }),
    /* @__PURE__ */ jsx("h3", { className: "text-lg font-medium text-foreground mb-2", children: "Failed to load form" }),
    /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground max-w-sm", children: error.message || "An unexpected error occurred" })
  ] });
}
function DefaultSuccessComponent({ message }) {
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center py-8 text-center", children: [
    /* @__PURE__ */ jsx("div", { className: "rounded-full bg-green-100 dark:bg-green-900 p-3 mb-4", children: /* @__PURE__ */ jsx(CheckCircle, { className: "h-6 w-6 text-green-600 dark:text-green-400" }) }),
    /* @__PURE__ */ jsx("h3", { className: "text-lg font-medium text-foreground mb-2", children: "Form Submitted" }),
    /* @__PURE__ */ 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 } = usePluginOverrides("form-builder", {
    localization: FORM_BUILDER_LOCALIZATION
  });
  const loc = localization || FORM_BUILDER_LOCALIZATION;
  const { form, isLoading, error } = useFormBySlug(slug);
  const submitMutation = useSubmitForm(slug);
  const [submitted, setSubmitted] = useState(false);
  const [finalSuccessMessage, setFinalSuccessMessage] = useState(
    null
  );
  const mergedFieldComponents = useMemo(
    () => ({
      ...overrideFieldComponents,
      ...propFieldComponents
    }),
    [overrideFieldComponents, propFieldComponents]
  );
  const { zodSchema, fieldConfig } = useMemo(() => {
    if (!form?.schema) {
      return { zodSchema: null, fieldConfig: {} };
    }
    try {
      const parsedSchema = JSON.parse(form.schema);
      const zod = formSchemaToZod(parsedSchema);
      const config = 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__ */ jsx("div", { className, children: /* @__PURE__ */ jsx(LoadingComponent, {}) });
  }
  if (error) {
    return /* @__PURE__ */ jsx("div", { className, children: /* @__PURE__ */ jsx(ErrorComponent, { error }) });
  }
  if (!form) {
    return /* @__PURE__ */ jsx("div", { className, children: /* @__PURE__ */ jsx(ErrorComponent, { error: new Error("Form not found") }) });
  }
  if (form.status !== "active") {
    return /* @__PURE__ */ jsx("div", { className, children: /* @__PURE__ */ jsx(
      ErrorComponent,
      {
        error: new Error("This form is not currently accepting submissions")
      }
    ) });
  }
  if (!zodSchema) {
    return /* @__PURE__ */ jsx("div", { className, children: /* @__PURE__ */ jsx(ErrorComponent, { error: new Error("Failed to parse form schema") }) });
  }
  if (submitted && finalSuccessMessage) {
    return /* @__PURE__ */ jsx("div", { className, children: /* @__PURE__ */ jsx(DefaultSuccessComponent, { message: finalSuccessMessage }) });
  }
  return /* @__PURE__ */ jsx("div", { className, "data-testid": "form-renderer", children: /* @__PURE__ */ jsx(
    SteppedAutoForm,
    {
      formSchema: zodSchema,
      fieldConfig,
      onSubmit: (values) => handleSubmit(values),
      isSubmitting: submitMutation.isPending,
      submitButtonText: submitButtonText || loc.FORM_BUILDER_BUTTON_SUBMIT
    }
  ) });
}

export { FormRenderer };
