import { db } from "@/lib/db";
import type { BlockOf } from "@/lib/blocks/schema";
import { messagesForSite } from "@/lib/services/org-translations";
import { parseFields } from "@/lib/services/forms";
import { issueFormToken } from "@/lib/public/forms";
import { Heading, Section } from "./section";
import { PublicForm } from "./public-form";
import type { RenderContext } from "./types";

/** Renders one of the site's own forms. A form id from another site (or a missing one) renders nothing. */
export async function FormBlock({ block, ctx }: { block: BlockOf<"form">; ctx: RenderContext }) {
  const { props, style } = block;
  const form = props.formId ? await db.formDefinition.findFirst({ where: { id: props.formId, siteId: ctx.siteId }, select: { id: true, status: true, fields: true, consentText: true } }) : null;
  if (!form) {
    return ctx.preview ? (
      <Section style={style} label={props.heading || "Form"}>
        <Heading>{props.heading}</Heading>
        <p className="rounded-md border border-dashed border-border p-4 text-sm opacity-70">No form selected, or it no longer exists. This note only shows in preview.</p>
      </Section>
    ) : null;
  }
  const fields = parseFields(form.fields);
  const text = await messagesForSite(ctx.siteId);
  return (
    <Section style={style} label={props.heading || "Form"}>
      <div className="mx-auto max-w-xl">
        <Heading>{props.heading}</Heading>
        {form.status === "PAUSED" ? (
          <p role="status" className="rounded-md border border-border p-4 text-sm">{text["forms.paused"]}</p>
        ) : (
          <>
            {ctx.preview ? <p className="mb-3 rounded-md border border-dashed border-border p-2 text-xs opacity-70">Preview: submitting is disabled.</p> : null}
            <PublicForm formId={form.id} fields={fields} consentText={form.consentText} token={ctx.preview ? "preview" : issueFormToken(form.id)} disabled={ctx.preview} text={text} />
          </>
        )}
      </div>
    </Section>
  );
}
