"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { createId } from "@paralleldrive/cuid2";
import {
  ArrowDownIcon,
  FileType2Icon,
  HandshakeIcon,
  MailIcon,
  TriangleAlertIcon,
  UserIcon,
  ZapIcon,
} from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
import { TSurveyFollowUpAction, TSurveyFollowUpTrigger } from "@formbricks/types/surveys/follow-up";
import { TSurvey } from "@formbricks/types/surveys/types";
import { getTextContent } from "@formbricks/types/surveys/validation";
import { TUserLocale } from "@formbricks/types/user";
import { recallToHeadline } from "@/lib/utils/recall";
import {
  TCreateSurveyFollowUpForm,
  TFollowUpEmailToUser,
  ZCreateSurveyFollowUpFormSchema,
} from "@/modules/survey/editor/types/survey-follow-up";
import FollowUpActionMultiEmailInput from "@/modules/survey/follow-ups/components/follow-up-action-multi-email-input";
import {
  type EmailSendToOption,
  buildEmailSendToOptions,
} from "@/modules/survey/follow-ups/lib/email-send-to-options";
import { buildFollowUpFormDefaultValues } from "@/modules/survey/follow-ups/lib/form-default-values";
import { sanitizeFollowUpBody } from "@/modules/survey/follow-ups/lib/sanitize-follow-up-body";
import { getElementIconMap } from "@/modules/survey/lib/elements";
import { AdvancedOptionToggle } from "@/modules/ui/components/advanced-option-toggle";
import { Alert, AlertTitle } from "@/modules/ui/components/alert";
import { Button } from "@/modules/ui/components/button";
import { Checkbox } from "@/modules/ui/components/checkbox";
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/modules/ui/components/dialog";
import { Editor } from "@/modules/ui/components/editor";
import {
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormProvider,
} from "@/modules/ui/components/form";
import { Input } from "@/modules/ui/components/input";
import { Label } from "@/modules/ui/components/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/modules/ui/components/select";
import { cn } from "@/modules/ui/lib/utils";

interface AddFollowUpModalProps {
  readonly localSurvey: TSurvey;
  readonly open: boolean;
  readonly setOpen: React.Dispatch<React.SetStateAction<boolean>>;
  readonly selectedLanguageCode: string;
  readonly mailFrom: string;
  readonly defaultValues?: Partial<TCreateSurveyFollowUpForm & { surveyFollowUpId: string }>;
  readonly mode?: "create" | "edit";
  readonly userEmail: string;
  readonly teamMemberDetails: TFollowUpEmailToUser[];
  readonly setLocalSurvey: React.Dispatch<React.SetStateAction<TSurvey>>;
  readonly locale: TUserLocale;
}

const withoutId = (ids: string[], id: string) => ids.filter((otherId) => otherId !== id);

export const FollowUpModal = ({
  localSurvey,
  open,
  setOpen,
  selectedLanguageCode,
  mailFrom,
  defaultValues,
  mode = "create",
  userEmail,
  teamMemberDetails,
  setLocalSurvey,
  locale,
}: AddFollowUpModalProps) => {
  const { t } = useTranslation();
  const ELEMENTS_ICON_MAP = getElementIconMap(t);
  const containerRef = useRef<HTMLDivElement>(null);
  const wasOpen = useRef(false);
  const [firstRender, setFirstRender] = useState(true);

  const emailSendToOptions: EmailSendToOption[] = useMemo(
    () =>
      buildEmailSendToOptions({
        survey: localSurvey,
        teamMemberDetails,
        userEmail,
        selectedLanguageCode,
        t,
      }),
    [localSurvey, selectedLanguageCode, teamMemberDetails, userEmail, t]
  );

  const form = useForm<TCreateSurveyFollowUpForm>({
    defaultValues: buildFollowUpFormDefaultValues({
      defaultValues,
      firstEmailSendToOptionId: emailSendToOptions[0]?.id,
      userEmail,
      t,
    }),
    resolver: zodResolver(ZCreateSurveyFollowUpFormSchema),
    mode: "onChange",
  });

  const formErrors = form.formState.errors;
  const formSubmitting = form.formState.isSubmitting;
  const triggerType = form.watch("triggerType");

  const handleSubmit = (data: TCreateSurveyFollowUpForm) => {
    if (data.triggerType === "endings" && data.endingIds?.length === 0) {
      toast.error(t("workspace.surveys.edit.follow_ups_modal_trigger_type_ending_warning"));
      return;
    }

    if (!emailSendToOptions.length) {
      toast.error(t("workspace.surveys.edit.follow_ups_modal_action_to_warning"));

      return;
    }

    if (Object.keys(formErrors).length > 0) {
      return;
    }

    if (data.triggerType === "endings") {
      if (!data.endingIds || !data.endingIds?.length) {
        form.setError("endingIds", {
          type: "manual",
          message: "Please select at least one ending",
        });
        return;
      }
    }

    const getProperties = (): TSurveyFollowUpTrigger["properties"] => {
      if (data.triggerType === "response") {
        return null;
      }

      if (data.endingIds && data.endingIds.length > 0) {
        return { endingIds: data.endingIds };
      }

      return null;
    };

    if (mode === "edit") {
      if (!defaultValues?.surveyFollowUpId) {
        toast.error(t("workspace.surveys.edit.follow_ups_modal_edit_no_id"));
        return;
      }

      const currentFollowUp = localSurvey.followUps.find(
        (followUp) => followUp.id === defaultValues.surveyFollowUpId
      );

      const sanitizedBody = sanitizeFollowUpBody(data.body);

      const updatedFollowUp = {
        id: defaultValues.surveyFollowUpId,
        createdAt: currentFollowUp?.createdAt ?? new Date(),
        updatedAt: new Date(),
        surveyId: localSurvey.id,
        name: data.followUpName,
        trigger: {
          type: data.triggerType,
          properties: getProperties(),
        },
        action: {
          type: "send-email" as TSurveyFollowUpAction["type"],
          properties: {
            to: data.emailTo,
            from: mailFrom,
            replyTo: data.replyTo,
            subject: data.subject,
            body: sanitizedBody,
            attachResponseData: data.attachResponseData,
            includeVariables: data.includeVariables,
            includeHiddenFields: data.includeHiddenFields,
          },
        },
      };

      toast.success(t("workspace.surveys.edit.follow_ups_modal_updated_successfull_toast"));
      setOpen(false);
      setLocalSurvey((prev) => {
        return {
          ...prev,
          followUps: prev.followUps.map((followUp) => {
            if (followUp.id === defaultValues.surveyFollowUpId) {
              return updatedFollowUp;
            }

            return followUp;
          }),
        };
      });
      return;
    }

    const sanitizedBody = sanitizeFollowUpBody(data.body);

    const newFollowUp = {
      id: createId(),
      createdAt: new Date(),
      updatedAt: new Date(),
      surveyId: localSurvey.id,
      name: data.followUpName,
      trigger: {
        type: data.triggerType,
        properties: getProperties(),
      },
      action: {
        type: "send-email" as TSurveyFollowUpAction["type"],
        properties: {
          to: data.emailTo,
          from: mailFrom,
          replyTo: data.replyTo,
          subject: data.subject,
          body: sanitizedBody,
          attachResponseData: data.attachResponseData,
          includeVariables: data.includeVariables,
          includeHiddenFields: data.includeHiddenFields,
        },
      },
    };

    toast.success(t("workspace.surveys.edit.follow_ups_modal_created_successfull_toast"));
    setOpen(false);
    form.reset();
    setLocalSurvey((prev) => {
      return {
        ...prev,
        followUps: [...prev.followUps, newFollowUp],
      };
    });
  };

  useEffect(() => {
    if (!open) {
      setFirstRender(true); // Reset when the modal is closed
    }
  }, [open]);

  useEffect(() => {
    let timeoutId: NodeJS.Timeout;

    if (open && containerRef.current) {
      timeoutId = setTimeout(() => {
        if (!containerRef.current) return;

        const scrollTop = containerRef.current.scrollTop;

        if (scrollTop > 0) {
          containerRef.current.scrollTo(0, 0);
        }
      }, 0);
    }

    // Clear the timeout when the effect is cleaned up or when open changes
    return () => {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
    };
  }, [open, firstRender]);

  useEffect(() => {
    if (open && !wasOpen.current && defaultValues) {
      // Same builder as the initial `defaultValues` above: two hand-maintained copies of this object
      // is what shipped #7218, and this one had already drifted — its `subject` fallback was a
      // hardcoded English string, so a non-English author editing a follow-up with no stored subject
      // got untranslated copy.
      form.reset(
        buildFollowUpFormDefaultValues({
          defaultValues,
          firstEmailSendToOptionId: emailSendToOptions[0]?.id,
          userEmail,
          t,
        })
      );
    }
    // Parent renders recreate defaultValues and recipient options. Only initialize on opening;
    // resetting an already-open form would silently replace the user's unsaved edits.
    wasOpen.current = open;
  }, [open, defaultValues, emailSendToOptions, form, userEmail, locale, t]);

  const handleModalClose = (open: boolean) => {
    if (!open) {
      form.reset();
    }
    setOpen(open);
  };

  const emailSendToVerifiedEmailOptions = emailSendToOptions.filter(
    (option) => option.type === "verifiedEmail"
  );
  const emailSendToElementOptions = emailSendToOptions.filter(
    (option) => option.type === "openTextElement" || option.type === "contactInfoElement"
  );
  const emailSendToHiddenFieldOptions = emailSendToOptions.filter((option) => option.type === "hiddenField");
  const userSendToEmailOptions = emailSendToOptions.filter((option) => option.type === "user");

  const getSelectItemIcon = (
    type: EmailSendToOption["type"]
  ): { icon: React.ReactNode; textClass?: string } => {
    switch (type) {
      case "verifiedEmail":
        return { icon: <MailIcon className="size-4" /> };
      case "hiddenField":
        // Same truncation as the other user-named labels: the row is `w-full` and a flex item does
        // not shrink below its content unless it clips, so a long field name would otherwise squeeze
        // the library key beside it (`secondaryLabel`) down to nothing.
        return {
          icon: <FileType2Icon className="size-4" />,
          textClass: "overflow-hidden text-ellipsis whitespace-nowrap",
        };
      case "user":
        return {
          icon: <UserIcon className="size-4" />,
          textClass: "overflow-hidden text-ellipsis whitespace-nowrap",
        };
      case "openTextElement":
      case "contactInfoElement":
        return {
          icon: (
            <div className="size-4">
              {ELEMENTS_ICON_MAP[type === "openTextElement" ? "openText" : "contactInfo"]}
            </div>
          ),
          textClass: "overflow-hidden text-ellipsis whitespace-nowrap",
        };
    }
  };

  const renderSelectItem = (option: EmailSendToOption) => {
    const { icon, textClass } = getSelectItemIcon(option.type);

    return (
      <SelectItem key={option.id} value={option.id}>
        <div className="flex w-full items-center gap-x-2">
          {icon}
          <span className={textClass}>{option.label}</span>
          {/* A shared Embedded Data field's library key — see `EmailSendToOption.secondaryLabel`. */}
          {option.secondaryLabel ? (
            <span className="ml-auto truncate pl-2 font-mono text-xs text-slate-500">
              {option.secondaryLabel}
            </span>
          ) : null}
        </div>
      </SelectItem>
    );
  };

  return (
    <Dialog open={open} onOpenChange={handleModalClose}>
      <DialogContent>
        <DialogHeader>
          <MailIcon />
          <DialogTitle>
            {mode === "edit"
              ? t("workspace.surveys.edit.follow_ups_modal_edit_heading")
              : t("workspace.surveys.edit.follow_ups_modal_create_heading")}
          </DialogTitle>
          <DialogDescription>{t("workspace.surveys.edit.follow_ups_modal_subheading")}</DialogDescription>
        </DialogHeader>

        <FormProvider {...form}>
          <form onSubmit={form.handleSubmit(handleSubmit)} className="contents">
            <DialogBody className="my-4">
              <div ref={containerRef} className="flex flex-col gap-y-4">
                {/* Follow up name */}
                <div className="flex flex-col gap-y-2">
                  <FormField
                    control={form.control}
                    name="followUpName"
                    render={({ field }) => {
                      return (
                        <FormItem>
                          <FormLabel htmlFor="follow-up-name">
                            {t("workspace.surveys.edit.follow_ups_modal_name_label")}:
                          </FormLabel>
                          <FormControl>
                            <Input
                              {...field}
                              type="text"
                              className="max-w-80"
                              isInvalid={!!formErrors.followUpName}
                              placeholder={t("workspace.surveys.edit.follow_ups_modal_name_placeholder")}
                            />
                          </FormControl>
                        </FormItem>
                      );
                    }}
                  />
                </div>

                {/* Trigger */}
                <div className="flex flex-col rounded-lg border border-slate-300">
                  <div className="flex items-center gap-x-2 rounded-t-lg border-b border-slate-300 bg-slate-100 px-4 py-2">
                    <div className="rounded-full border border-slate-300 bg-white p-1">
                      <ZapIcon className="size-3 text-slate-500" />
                    </div>
                    <h2 className="text-md font-semibold text-slate-900">
                      {t("workspace.surveys.edit.follow_ups_modal_trigger_label")}
                    </h2>
                  </div>

                  <div className="flex flex-col gap-4 p-4">
                    <FormField
                      control={form.control}
                      name="triggerType"
                      render={({ field }) => {
                        return (
                          <FormItem>
                            <div className="flex flex-col gap-y-2">
                              <FormLabel htmlFor="triggerType">
                                {t("workspace.surveys.edit.follow_ups_modal_trigger_description")}
                              </FormLabel>
                              <div className="max-w-80">
                                <Select
                                  defaultValue={field.value}
                                  onValueChange={(value) => field.onChange(value)}>
                                  <SelectTrigger>
                                    <SelectValue />
                                  </SelectTrigger>

                                  <SelectContent>
                                    <SelectItem value="response">
                                      {t("workspace.surveys.edit.follow_ups_modal_trigger_type_response")}
                                    </SelectItem>
                                    {localSurvey.endings.length > 0 ? (
                                      <SelectItem value="endings">
                                        {t("workspace.surveys.edit.follow_ups_modal_trigger_type_ending")}
                                      </SelectItem>
                                    ) : null}
                                  </SelectContent>
                                </Select>

                                {triggerType === "endings" && !localSurvey.endings.length ? (
                                  <Alert variant="warning" size="small">
                                    <AlertTitle>
                                      {t(
                                        "workspace.surveys.edit.follow_ups_modal_trigger_type_ending_warning"
                                      )}
                                    </AlertTitle>
                                  </Alert>
                                ) : null}
                              </div>
                            </div>
                          </FormItem>
                        );
                      }}
                    />

                    {localSurvey.endings.length > 0 && triggerType === "endings" ? (
                      <FormField
                        control={form.control}
                        name="endingIds"
                        render={({ field }) => {
                          return (
                            <div className="flex flex-col gap-y-2">
                              <h3 className="text-sm font-medium text-slate-700">
                                {t("workspace.surveys.edit.follow_ups_modal_trigger_type_ending_select")}
                              </h3>
                              <div className="flex flex-col gap-y-2">
                                {localSurvey.endings.map((ending) => {
                                  const getEndingLabel = (): string => {
                                    if (ending.type === "endScreen") {
                                      return (
                                        getTextContent(
                                          recallToHeadline(
                                            ending.headline ?? {},
                                            localSurvey,
                                            false,
                                            selectedLanguageCode
                                          )[selectedLanguageCode]
                                        ) || "Ending"
                                      );
                                    }

                                    return ending.label || ending.url || "Ending";
                                  };

                                  return (
                                    <Label
                                      key={ending.id}
                                      className="w-80 cursor-pointer rounded-md border border-slate-300 bg-slate-50 px-3 py-2 hover:bg-slate-100"
                                      htmlFor={`ending-${ending.id}`}>
                                      <div className="flex items-center gap-x-2">
                                        <Checkbox
                                          className="inline"
                                          checked={field.value?.includes(ending.id)}
                                          id={`ending-${ending.id}`}
                                          onCheckedChange={(checked) => {
                                            if (checked) {
                                              form.setValue("endingIds", [...(field.value ?? []), ending.id]);
                                            } else {
                                              form.setValue(
                                                "endingIds",
                                                withoutId(field.value ?? [], ending.id)
                                              );
                                            }
                                          }}
                                        />
                                        <HandshakeIcon className="size-4 min-h-4 min-w-4" />
                                        <span className="overflow-hidden text-ellipsis whitespace-nowrap text-slate-900">
                                          {getEndingLabel()}
                                        </span>
                                      </div>
                                    </Label>
                                  );
                                })}

                                {formErrors.endingIds ? (
                                  <div className="mt-2">
                                    <span className="text-red-500">{formErrors.endingIds.message}</span>
                                  </div>
                                ) : null}
                              </div>
                            </div>
                          );
                        }}
                      />
                    ) : null}
                  </div>
                </div>

                {/* Arrow */}
                <div className="flex items-center justify-center">
                  <ArrowDownIcon className="size-4 text-slate-500" />
                </div>

                {/* Action */}
                <div className="flex flex-col rounded-lg border border-slate-300">
                  <div className="flex items-center gap-x-2 rounded-t-lg border-b border-slate-300 bg-slate-100 px-4 py-2">
                    <div className="rounded-full border border-slate-300 bg-white p-1">
                      <MailIcon className="size-3 text-slate-500" />
                    </div>
                    <h2 className="text-md font-semibold text-slate-900">
                      {t("workspace.surveys.edit.follow_ups_modal_action_label")}
                    </h2>
                  </div>

                  {/* email setup */}
                  <div className="flex flex-col gap-y-4 p-4">
                    <h2 className="text-md font-semibold text-slate-900">
                      {t("workspace.surveys.edit.follow_ups_modal_action_email_settings")}
                    </h2>

                    {/* To */}
                    <div className="flex flex-col gap-y-2">
                      <FormField
                        control={form.control}
                        name="emailTo"
                        render={({ field }) => {
                          return (
                            <div className="flex flex-col gap-y-2">
                              <FormLabel htmlFor="emailTo" className="font-medium">
                                {t("workspace.surveys.edit.follow_ups_modal_action_to_label")}
                              </FormLabel>
                              <FormDescription
                                className={cn(
                                  "text-sm",
                                  formErrors.emailTo ? "text-red-500" : "text-slate-500"
                                )}>
                                {t("workspace.surveys.edit.follow_ups_modal_action_to_description")}
                              </FormDescription>

                              {emailSendToOptions.length === 0 && (
                                <div className="mt-4 flex items-start text-yellow-600">
                                  <TriangleAlertIcon
                                    className="mr-2 size-5 min-h-5 min-w-5"
                                    aria-hidden="true"
                                  />
                                  <p className="text-sm">
                                    {t("workspace.surveys.edit.follow_ups_modal_action_to_warning")}
                                  </p>
                                </div>
                              )}

                              {emailSendToOptions.length > 0 ? (
                                <div className="max-w-80">
                                  <FormControl>
                                    <Select
                                      defaultValue={field.value}
                                      onValueChange={(value) => {
                                        const selectedOption = emailSendToOptions.find(
                                          (option) => option.id === value
                                        );
                                        if (!selectedOption) return;

                                        field.onChange(selectedOption.id);
                                      }}>
                                      <SelectTrigger className="overflow-hidden text-ellipsis whitespace-nowrap">
                                        <SelectValue />
                                      </SelectTrigger>

                                      <SelectContent>
                                        {emailSendToVerifiedEmailOptions.length > 0 ||
                                        emailSendToElementOptions.length > 0 ? (
                                          <div className="flex flex-col">
                                            <div className="flex items-center gap-x-2 p-2">
                                              <p className="text-sm text-slate-500">
                                                {t("common.questions")}
                                              </p>
                                            </div>

                                            {emailSendToVerifiedEmailOptions.map((option) =>
                                              renderSelectItem(option)
                                            )}

                                            {emailSendToElementOptions.map((option) =>
                                              renderSelectItem(option)
                                            )}
                                          </div>
                                        ) : null}

                                        {/*
                                          Ingested fields only, under the whole category's name:
                                          `buildEmailSendToOptions` lists `getIngestedEmbeddedFields`,
                                          because an address a recipient is read from arrives with the
                                          response rather than being computed during it. The heading
                                          names the category the rows belong to, not everything in it.
                                        */}
                                        {emailSendToHiddenFieldOptions.length > 0 ? (
                                          <div className="flex flex-col">
                                            <div className="flex gap-x-2 p-2">
                                              <p className="text-sm text-slate-500">
                                                {t("common.embedded_data")}
                                              </p>
                                            </div>

                                            {emailSendToHiddenFieldOptions.map((option) =>
                                              renderSelectItem(option)
                                            )}
                                          </div>
                                        ) : null}

                                        {userSendToEmailOptions.length > 0 ? (
                                          <div className="flex flex-col">
                                            <div className="flex gap-x-2 p-2">
                                              <p className="text-sm text-slate-500">{t("common.users")}</p>
                                            </div>

                                            {userSendToEmailOptions.map((option) => renderSelectItem(option))}
                                          </div>
                                        ) : null}
                                      </SelectContent>
                                    </Select>
                                  </FormControl>
                                </div>
                              ) : null}
                            </div>
                          );
                        }}
                      />
                    </div>

                    {/* From */}
                    <div className="flex flex-col gap-y-2">
                      <h3 className="text-sm font-medium text-slate-900">
                        {t("workspace.surveys.edit.follow_ups_modal_action_from_label")}
                      </h3>
                      <p className="text-sm text-slate-500">
                        {t("workspace.surveys.edit.follow_ups_modal_action_from_description")}
                      </p>

                      <div className="w-fit rounded-md border border-slate-200 bg-slate-100 px-2 py-1">
                        <span className="text-sm text-slate-900">{mailFrom}</span>
                      </div>
                    </div>

                    {/* Reply To */}
                    <div className="flex flex-col gap-y-2">
                      <FormField
                        control={form.control}
                        name="replyTo"
                        render={({ field }) => {
                          return (
                            <FormItem>
                              <FormLabel htmlFor="replyTo">
                                {t("workspace.surveys.edit.follow_ups_modal_action_replyTo_label")}
                              </FormLabel>
                              <FormDescription className="text-sm text-slate-500">
                                {t("workspace.surveys.edit.follow_ups_modal_action_replyTo_description")}
                              </FormDescription>
                              <FormControl>
                                <FollowUpActionMultiEmailInput
                                  emails={field.value}
                                  setEmails={field.onChange}
                                  isInvalid={!!formErrors.replyTo}
                                />
                              </FormControl>
                            </FormItem>
                          );
                        }}
                      />
                    </div>
                  </div>

                  {/* email content */}
                  <div className="flex flex-col gap-y-4 p-4">
                    <h2 className="text-md font-semibold text-slate-900">
                      {t("workspace.surveys.edit.follow_ups_modal_action_email_content")}
                    </h2>
                    <FormField
                      control={form.control}
                      name="subject"
                      render={({ field }) => {
                        return (
                          <FormItem>
                            <div className="flex flex-col gap-y-2">
                              <FormLabel>
                                {t("workspace.surveys.edit.follow_ups_modal_action_subject_label")}
                              </FormLabel>
                              <FormControl>
                                <Input
                                  {...field}
                                  className="max-w-80"
                                  placeholder={t(
                                    "workspace.surveys.edit.follow_ups_modal_action_subject_placeholder"
                                  )}
                                  isInvalid={!!formErrors.subject}
                                />
                              </FormControl>
                            </div>
                          </FormItem>
                        );
                      }}
                    />

                    <FormField
                      control={form.control}
                      name="body"
                      render={({ field }) => {
                        return (
                          <FormItem>
                            <div className="flex flex-col gap-y-2">
                              <FormLabel
                                className={cn(
                                  "font-medium",
                                  formErrors.body ? "text-red-500" : "text-slate-700"
                                )}>
                                {t("workspace.surveys.edit.follow_ups_modal_action_body_label")}
                              </FormLabel>
                              <FormControl>
                                <Editor
                                  disableLists
                                  excludedToolbarItems={["blockType"]}
                                  getText={() => field.value}
                                  setText={(v: string) => {
                                    field.onChange(v);
                                  }}
                                  firstRender={firstRender}
                                  setFirstRender={setFirstRender}
                                  placeholder={t(
                                    "workspace.surveys.edit.follow_ups_modal_action_body_placeholder"
                                  )}
                                  onEmptyChange={(isEmpty) => {
                                    if (isEmpty) {
                                      if (!formErrors.body) {
                                        form.setError("body", {
                                          type: "manual",
                                          message: "Body is required",
                                        });
                                      }
                                    } else {
                                      if (formErrors.body) {
                                        form.clearErrors("body");
                                      }
                                    }
                                  }}
                                  isInvalid={!!formErrors.body}
                                  localSurvey={localSurvey}
                                  elementId="follow-up"
                                  selectedLanguageCode={selectedLanguageCode}
                                />
                              </FormControl>

                              {formErrors.body ? (
                                <div>
                                  <span className="text-sm text-red-500">{formErrors.body.message}</span>
                                </div>
                              ) : null}
                            </div>
                          </FormItem>
                        );
                      }}
                    />

                    <FormField
                      control={form.control}
                      name="attachResponseData"
                      render={({ field }) => {
                        return (
                          <FormItem>
                            <AdvancedOptionToggle
                              htmlId="attachResponseData"
                              isChecked={field.value}
                              onToggle={(checked) => field.onChange(checked)}
                              title={t(
                                "workspace.surveys.edit.follow_ups_modal_action_attach_response_data_label"
                              )}
                              description={t(
                                "workspace.surveys.edit.follow_ups_modal_action_attach_response_data_description"
                              )}
                              customContainerClass="p-0"
                              childBorder>
                              <div className="flex w-full flex-col gap-4 p-4">
                                <FormField
                                  control={form.control}
                                  name="includeVariables"
                                  render={({ field: variablesField }) => (
                                    <FormItem>
                                      <div className="flex items-center gap-x-2">
                                        <Checkbox
                                          id="includeVariables"
                                          checked={variablesField.value}
                                          onCheckedChange={(checked) => variablesField.onChange(checked)}
                                          disabled={!field.value}
                                        />
                                        <FormLabel htmlFor="includeVariables" className="font-medium">
                                          {t("workspace.surveys.edit.follow_ups_include_variables")}
                                        </FormLabel>
                                      </div>
                                    </FormItem>
                                  )}
                                />

                                <FormField
                                  control={form.control}
                                  name="includeHiddenFields"
                                  render={({ field: hiddenFieldsField }) => (
                                    <FormItem>
                                      <div className="flex items-center gap-x-2">
                                        <Checkbox
                                          id="includeHiddenFields"
                                          checked={hiddenFieldsField.value}
                                          onCheckedChange={(checked) => hiddenFieldsField.onChange(checked)}
                                          disabled={!field.value}
                                        />
                                        <FormLabel htmlFor="includeHiddenFields" className="font-medium">
                                          {t("workspace.surveys.edit.follow_ups_include_hidden_fields")}
                                        </FormLabel>
                                      </div>
                                    </FormItem>
                                  )}
                                />
                              </div>
                            </AdvancedOptionToggle>
                          </FormItem>
                        );
                      }}
                    />
                  </div>
                </div>
              </div>
            </DialogBody>

            <DialogFooter>
              <Button
                type="button"
                variant="secondary"
                onClick={() => {
                  setOpen(false);
                  form.reset();
                }}>
                {t("common.cancel")}
              </Button>

              <Button loading={formSubmitting}>{t("common.save")}</Button>
            </DialogFooter>
          </form>
        </FormProvider>
      </DialogContent>
    </Dialog>
  );
};
