import type { TFunction } from "i18next";
import { getIngestedEmbeddedFields } from "@formbricks/types/embedded-data-resolver";
import { TSurveyElementTypeEnum } from "@formbricks/types/surveys/elements";
import type { TSurvey } from "@formbricks/types/surveys/types";
import { getTextContent } from "@formbricks/types/surveys/validation";
import { isLiteralEmailRecipient } from "@formbricks/workflows";
import { normalizeEmailForComparison } from "@/lib/utils/email";
import { recallToHeadline } from "@/lib/utils/recall";
import type { TFollowUpEmailToUser } from "@/modules/survey/editor/types/survey-follow-up";
import { getElementsFromBlocks } from "@/modules/survey/lib/client-utils";

/** A selectable recipient for a survey-response email (Follow-Ups + workflow send_email share this). */
export interface EmailSendToOption {
  type: "openTextElement" | "contactInfoElement" | "hiddenField" | "user" | "verifiedEmail";
  label: string;
  id: string;
  /**
   * A shared Embedded Data field's workspace library key, rendered beside the label (ENG-1853).
   * Absent for every other kind of recipient, and for a field the survey owns — see
   * `TReadableField`'s `secondaryLabel` for why a key earns its own dim line next to a name.
   */
  secondaryLabel?: string;
}

/**
 * Builds the "who to send to" options for a survey-response email, identical to the survey
 * Follow-Ups recipient dropdown: OpenText(email) + ContactInfo(email.show) elements, hidden fields,
 * an optional verified-email entry, and the team roster (with the current user surfaced as
 * "Yourself"). Shared by `FollowUpModal` and the workflow `send_email` inspector form. Without a
 * survey (a Webhook workflow's email) only the team roster is offered.
 */
export const buildEmailSendToOptions = ({
  survey,
  teamMemberDetails,
  userEmail,
  selectedLanguageCode,
  t,
}: {
  survey: TSurvey | null;
  teamMemberDetails: TFollowUpEmailToUser[];
  userEmail: string;
  selectedLanguageCode: string;
  t: TFunction;
}): EmailSendToOption[] => {
  const elements = survey ? getElementsFromBlocks(survey.blocks) : [];

  const openTextAndContactElements = elements.filter((element) => {
    if (element.type === TSurveyElementTypeEnum.ContactInfo) {
      return element.email.show;
    }

    if (element.type === TSurveyElementTypeEnum.OpenText) {
      return element.inputType === "email";
    }

    return false;
  });

  // ENG-2628: the survey's rows, like every other reader. The editor's Embedded Data cards edit them
  // directly, so this picker — which WRITES a recipient — and `follow-up-item.tsx`, which renders the
  // stored one back, still read the same instant's definitions.
  //
  // ENG-1853: the whole pair rather than the storage keys alone, because the row is now labelled by
  // the field's NAME. The id is still the storage key, so a recipient stored before this — and
  // `findEmailSendToOption`, which matches on it — is unaffected; only what the author reads changed.
  const ingestedFields = survey ? getIngestedEmbeddedFields(survey) : [];

  const updatedTeamMemberDetails = teamMemberDetails.map((teamMemberDetail) =>
    teamMemberDetail.email === userEmail ? { name: "Yourself", email: userEmail } : teamMemberDetail
  );

  const isUserEmailInTeamMemberDetails = updatedTeamMemberDetails.some(
    (teamMemberDetail) => teamMemberDetail.email === userEmail
  );

  const updatedTeamMembers = isUserEmailInTeamMemberDetails
    ? updatedTeamMemberDetails
    : [...updatedTeamMemberDetails, { email: userEmail, name: "Yourself" }];

  const verifiedEmailOption: EmailSendToOption[] = survey?.isVerifyEmailEnabled
    ? [{ label: t("common.verified_email"), id: "verifiedEmail", type: "verifiedEmail" }]
    : [];

  return [
    ...verifiedEmailOption,
    ...openTextAndContactElements.map((element) => ({
      // `survey` is set whenever there are elements; the guard only narrows the type.
      label: survey
        ? getTextContent(
            recallToHeadline(element.headline, survey, false, selectedLanguageCode)[selectedLanguageCode]
          )
        : element.id,
      id: element.id,
      type: (element.type === TSurveyElementTypeEnum.OpenText
        ? "openTextElement"
        : "contactInfoElement") as EmailSendToOption["type"],
    })),
    ...ingestedFields.map(({ field, link }) => ({
      label: field.name.trim() === "" ? link.storageKey : field.name,
      id: link.storageKey,
      type: "hiddenField" as EmailSendToOption["type"],
      secondaryLabel: field.key ?? undefined,
    })),
    ...updatedTeamMembers.map((member) => ({
      label: `${member.name} (${member.email})`,
      id: member.email,
      type: "user" as EmailSendToOption["type"],
    })),
  ];
};

/**
 * Resolves a stored `to` value to the option it selects, or `undefined` when none matches.
 *
 * A `user` option's id is an email address, so it is matched through `normalizeEmailForComparison` —
 * the exact rule the runtime allowlist uses when it builds the member-email set and checks a
 * recipient against it (`verifyRecipientsAllowed`, and the runner's send-time backstop). Without
 * that, a `to` stored as `Manager@Example.com` through the v3 API or an MCP tool would send fine yet
 * be reported as unavailable in the editor. Element and hidden-field ids are opaque, case-sensitive
 * identifiers rather than emails, so they keep matching exactly.
 *
 * That email rule is applied only to a value the runtime itself would treat as a literal email, so
 * the gate is `isLiteralEmailRecipient` rather than an inline check: it is the same predicate the
 * enable-time allowlist and the runner classify with, so the two cannot disagree about what an email
 * is even if the underlying `z.email()` rule changes. It matters because
 * `normalizeEmailForComparison` also trims, and `z.email()` rejects surrounding whitespace: a `to`
 * stored as `" alice@example.com"` is *not* a literal recipient at runtime, so it is never
 * allowlist-checked and every run fails resolving it as an element id. Trimming it into a member
 * match here would replace the "Not available" warning — which is correct for that value — with a
 * normal-looking selection.
 */
export const findEmailSendToOption = (
  options: EmailSendToOption[],
  value: string
): EmailSendToOption | undefined => {
  if (value === "") return undefined;

  const normalizedEmail = isLiteralEmailRecipient(value) ? normalizeEmailForComparison(value) : null;
  return options.find((option) =>
    option.type === "user"
      ? normalizedEmail !== null && normalizeEmailForComparison(option.id) === normalizedEmail
      : option.id === value
  );
};
