import { redirect } from "next/navigation";
import { after } from "next/server";
import { MailGate } from "@/components/mail-gate";
import type { MemberMailboxViewState } from "@/components/mail-members-panel";
import type { MailSetupSection } from "@/components/mail-setup-workspace";
import { requireSessionUser } from "@/lib/auth";
import {
  getAiAssistOverviewByOwnerEmail,
  getManagedMembersByOwnerEmail,
  type MailAiAssistOverview,
  type ManagedMailboxMember,
} from "@/lib/mail-automation";
import {
  getAutoSendOverviewByOwnerEmail,
  type MailAutoSendOverview,
} from "@/lib/mail-auto-send";
import {
  getMailBillingCancellationOverviewByOwnerEmail,
  type MailBillingCancellationOverview,
} from "@/lib/billing-cancellation";
import type { MailListSortOrder } from "@/lib/mail-layout";
import { plainTextToHtml, sanitizeMailboxHtml } from "@/lib/mail-html";
import {
  getMailAppOverviewByEmail,
  getMailLayoutPreferencesByEmail,
  getMailSetupOverviewByEmail,
  refreshMailboxIfStaleByEmail,
  type MailMessageDetail,
  type MailMessageFilter,
  type MailSearchField,
} from "@/lib/official-mail";
import { normalizeMailboxPageSize } from "@/lib/mailbox-page-size";
import {
  countMailBillingSeatsFromManagedMembers,
  createMailPlanSummary,
  hasComplimentaryGrowthPlanByEmail,
} from "@/lib/mail-billing";
import {
  pickMailBillingHistoryPage,
  pickMailBillingHistoryRangePreset,
  pickMailBillingTab,
  resolveMailBillingHistoryState,
  type MailBillingHistoryState,
} from "@/lib/mail-billing-history";
import {
  getMailBillingOwnershipByEmail,
  getMailBillingHistoryByOwnerEmail,
  getMailBillingOverviewByOwnerEmail,
  type MailBillingHistoryPage,
  type MailBillingOverview,
} from "@/lib/toss-pay";

type MailPageProps = {
  searchParams?: Promise<Record<string, string | string[] | undefined>>;
};

type NoticeTone = "error" | "success";

function pickParam(value: string | string[] | undefined) {
  return Array.isArray(value) ? value[0] : value;
}

function pickMessageFilter(value: string | string[] | undefined): MailMessageFilter {
  const picked = pickParam(value);

  if (picked === "unread" || picked === "important" || picked === "attachments") {
    return picked;
  }

  return "all";
}

function pickPositivePage(value: string | string[] | undefined) {
  const picked = Number(pickParam(value) ?? "1");

  if (!Number.isFinite(picked) || picked < 1) {
    return 1;
  }

  return Math.floor(picked);
}

function pickPositiveInteger(value: string | string[] | undefined) {
  const picked = Number(pickParam(value) ?? "");

  if (!Number.isFinite(picked) || picked < 1) {
    return null;
  }

  return Math.floor(picked);
}

function pickSearchField(value: string | string[] | undefined): MailSearchField {
  const picked = pickParam(value);

  if (picked === "from" || picked === "to" || picked === "subject" || picked === "body") {
    return picked;
  }

  return "all";
}

function pickComposeMode(value: string | string[] | undefined) {
  const picked = pickParam(value);

  if (picked === "reply" || picked === "replyAll" || picked === "forward") {
    return picked;
  }

  return "new";
}

function pickSortOrder(
  value: string | string[] | undefined,
  fallback: MailListSortOrder,
): MailListSortOrder {
  const picked = pickParam(value);

  return picked === "oldest" || picked === "latest" ? picked : fallback;
}

function padNumber(value: number) {
  return String(value).padStart(2, "0");
}

function formatComposeFullDate(value: string) {
  const date = new Date(value);
  const weekdays = ["일", "월", "화", "수", "목", "금", "토"];
  const hours = date.getHours();
  const period = hours >= 12 ? "PM" : "AM";
  const hour12 = hours % 12 || 12;

  return `${date.getFullYear()}.${padNumber(date.getMonth() + 1)}.${padNumber(
    date.getDate(),
  )} (${weekdays[date.getDay()]}) ${hour12}:${padNumber(date.getMinutes())} ${period}`;
}

function escapeHtml(value: string) {
  return value
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

function prefixedSubject(subject: string, prefix: "Fwd:" | "Re:") {
  const trimmed = subject.trim();

  if (!trimmed) {
    return prefix;
  }

  return trimmed.toLowerCase().startsWith(prefix.toLowerCase())
    ? trimmed
    : `${prefix} ${trimmed}`;
}

function splitAddressList(value: string) {
  return value
    .split(",")
    .map((address) => address.trim())
    .filter(Boolean);
}

function originalMessageHtml(message: MailMessageDetail) {
  return (
    message.bodyHtml?.trim() ||
    message.bodyHtmlDisplay?.trim() ||
    plainTextToHtml(message.bodyText.trim() || message.snippet.trim() || "")
  );
}

function quotedMessageBody(message: MailMessageDetail) {
  return [
    "",
    "",
    "---------- 원본 메일 ----------",
    `보낸사람: ${message.fromName ? `${message.fromName} <${message.fromAddress}>` : message.fromAddress}`,
    `보낸시각: ${formatComposeFullDate(message.receivedAt)}`,
    `제목: ${message.subject}`,
    `받는사람: ${message.toAddresses}`,
    "",
    message.bodyText.trim() || message.snippet.trim() || "",
  ].join("\n");
}

function quotedMessageHtml(
  message: MailMessageDetail,
  action: "forward" | "reply" | "replyAll",
) {
  const sender = message.fromName
    ? `${message.fromName} <${message.fromAddress}>`
    : message.fromAddress;
  const bodyHtml = originalMessageHtml(message);
  const replyHeader = `${formatComposeFullDate(message.receivedAt)}, ${sender}님이 작성:`;

  if (action === "forward") {
    return [
      "<p><br></p>",
      "<p><br></p>",
      "<p>---------- 원본 메일 ----------</p>",
      `<p>보낸사람: ${escapeHtml(sender)}</p>`,
      `<p>보낸시각: ${escapeHtml(formatComposeFullDate(message.receivedAt))}</p>`,
      `<p>제목: ${escapeHtml(message.subject)}</p>`,
      `<p>받는사람: ${escapeHtml(message.toAddresses)}</p>`,
      "<p><br></p>",
      `<blockquote>${bodyHtml}</blockquote>`,
    ].join("");
  }

  return [
    "<p><br></p>",
    "<p><br></p>",
    `<div>${escapeHtml(replyHeader)}</div>`,
    `<blockquote>${bodyHtml}</blockquote>`,
  ].join("");
}

function resolveSourceComposeDefaults(input: {
  bcc: string;
  body: string;
  bodyHtml: string;
  cc: string;
  mode: "forward" | "new" | "reply" | "replyAll";
  message: MailMessageDetail | null;
  ownAddresses: string[];
  subject: string;
  to: string;
}) {
  if (input.mode === "new" || !input.message) {
    return {
      bcc: input.bcc,
      body: input.body,
      bodyHtml: input.bodyHtml,
      cc: input.cc,
      subject: input.subject,
      to: input.to,
    };
  }

  if (input.mode === "forward") {
    return {
      bcc: "",
      body: quotedMessageBody(input.message),
      bodyHtml: quotedMessageHtml(input.message, "forward"),
      cc: "",
      subject: prefixedSubject(input.message.subject, "Fwd:"),
      to: "",
    };
  }

  if (input.mode === "replyAll") {
    const ownAddresses = new Set(input.ownAddresses.map((address) => address.toLowerCase()));
    const recipients = [
      input.message.fromAddress,
      ...splitAddressList(input.message.toAddresses),
    ].filter((address, index, array) => {
      const normalized = address.toLowerCase();

      return (
        !ownAddresses.has(normalized) &&
        array.findIndex((item) => item.toLowerCase() === normalized) === index
      );
    });

    return {
      bcc: "",
      body: quotedMessageBody(input.message),
      bodyHtml: quotedMessageHtml(input.message, "replyAll"),
      cc: recipients.slice(1).join(", "),
      subject: prefixedSubject(input.message.subject, "Re:"),
      to: recipients[0] ?? "",
    };
  }

  return {
    bcc: "",
    body: quotedMessageBody(input.message),
    bodyHtml: quotedMessageHtml(input.message, "reply"),
    cc: "",
    subject: prefixedSubject(input.message.subject, "Re:"),
    to: input.message.fromAddress,
  };
}

const noticeMap: Record<string, { tone: NoticeTone; message: string }> = {
  "domain-required": {
    tone: "error",
    message: "도메인과 대표 메일 아이디를 모두 입력해주세요.",
  },
  "domain-taken": {
    tone: "error",
    message: "이미 다른 계정에서 사용 중인 도메인입니다.",
  },
  "mailbox-taken": {
    tone: "error",
    message: "이미 등록된 대표 메일 주소입니다. 다른 메일 아이디를 사용해주세요.",
  },
  "invalid-local-part": {
    tone: "error",
    message: "메일 아이디는 영문 소문자, 숫자, 점(.), 하이픈(-), 밑줄(_)만 사용할 수 있습니다.",
  },
  "password-required": {
    tone: "error",
    message: "변경할 비밀번호와 확인 값을 모두 입력해주세요.",
  },
  "password-mismatch": {
    tone: "error",
    message: "비밀번호와 확인 값이 서로 다릅니다.",
  },
  "security-password-required": {
    tone: "error",
    message: "대표 메일 비밀번호 정보가 없어 다시 저장이 필요합니다. 계정 설정에서 비밀번호를 먼저 등록해주세요.",
  },
  "mail-config": {
    tone: "error",
    message: "메일 서버 연결 설정이 누락되어 있습니다. 관리자에게 문의해주세요.",
  },
  "mail-auth": {
    tone: "error",
    message: "메일 서버 인증에 실패했습니다. 잠시 후 다시 시도해주세요.",
  },
  "mail-domain-exists": {
    tone: "error",
    message:
      "같은 도메인이 이미 등록되어 있어 자동 연결을 멈췄습니다. 기존 도메인 사용 상태를 먼저 확인해주세요.",
  },
  "mail-setup": {
    tone: "error",
    message:
      "도메인 또는 메일함 생성 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.",
  },
  "dkim-regeneration": {
    tone: "error",
    message:
      "DKIM 키를 다시 발급하지 못했습니다. 잠시 후 다시 시도하거나 관리자에게 문의해주세요.",
  },
  "dkim-usage": {
    tone: "error",
    message: "DKIM 사용 설정을 변경하지 못했습니다. 잠시 후 다시 시도해주세요.",
  },
  "verify-pending": {
    tone: "error",
    message:
      "현재 저장된 DNS 값 또는 메일 서버 등록 상태가 일치하지 않습니다. DNS 반영과 메일함 연결 상태를 다시 확인해주세요.",
  },
  provisioned: {
    tone: "success",
    message:
      "대표 메일함 등록이 완료되었습니다. 아래 DNS 값을 복사해 도메인 관리 화면에 입력하세요.",
  },
  "dkim-regenerated": {
    tone: "success",
    message:
      "새 DKIM 키를 발급했습니다. DNS의 DKIM 값을 새 값으로 바꾼 뒤 연결 상태를 확인해주세요.",
  },
  "dkim-enabled": {
    tone: "success",
    message: "DKIM 사용을 켰습니다. DNS의 DKIM 값이 정상인지 연결 상태를 확인해주세요.",
  },
  "dkim-disabled": {
    tone: "success",
    message: "DKIM 검증을 건너뛰도록 설정했습니다. SPF와 DMARC는 계속 필요합니다.",
  },
  "password-updated": {
    tone: "success",
    message: "대표 메일 비밀번호를 변경했습니다. 로그인, 웹메일, IMAP/SMTP에 같은 값이 적용됩니다.",
  },
  verified: {
    tone: "success",
    message: "DNS 검증이 완료되었습니다. 이제 메일함에서 바로 송수신을 시작할 수 있습니다.",
  },
  "ai-assist-saved": {
    tone: "success",
    message: "AI 어시스트 브릿지를 저장했습니다. 이제 새 메일 요약과 답장 릴레이가 활성화됩니다.",
  },
  "ai-assist-disabled": {
    tone: "success",
    message: "AI 어시스트 브릿지를 비활성화했습니다.",
  },
  "auto-send-saved": {
    tone: "success",
    message: "자동발송 예약 설정을 저장했습니다.",
  },
  "auto-send-disabled": {
    tone: "success",
    message: "자동발송 예약을 비활성화했습니다.",
  },
  "auto-send-invalid": {
    tone: "error",
    message: "자동발송 예약 값이 올바르지 않습니다. 다시 확인해주세요.",
  },
  "auto-send-invalid-email": {
    tone: "error",
    message: "자동발송 수신자 이메일 형식이 올바르지 않습니다.",
  },
  "auto-send-required": {
    tone: "error",
    message: "예약 활성화에는 수신자와 제목·본문이 포함된 보낼 내용이 필요합니다.",
  },
  "auto-send-plan-required": {
    tone: "error",
    message: "자동발송 예약은 성장 플랜에서 사용할 수 있습니다.",
  },
  "member-created": {
    tone: "success",
    message: "새 멤버 메일함을 추가했습니다.",
  },
  "member-updated": {
    tone: "success",
    message: "멤버 메일함 정보를 수정했습니다.",
  },
  "member-deleted": {
    tone: "success",
    message: "멤버 메일함을 삭제했습니다.",
  },
  send: {
    tone: "success",
    message: "메일을 전송했습니다.",
  },
  "send-individual": {
    tone: "success",
    message: "메일을 개별 발송했습니다.",
  },
  draft: {
    tone: "success",
    message: "초안을 저장했습니다.",
  },
  refresh: {
    tone: "success",
    message: "메일함을 다시 동기화했습니다.",
  },
  "mark-read": {
    tone: "success",
    message: "선택한 메일을 읽음 처리했습니다.",
  },
  "mark-unread": {
    tone: "success",
    message: "선택한 메일을 안읽음 처리했습니다.",
  },
  "move-trash": {
    tone: "success",
    message: "선택한 메일을 휴지통으로 이동했습니다.",
  },
  "move-trash-delete": {
    tone: "success",
    message: "선택한 메일을 휴지통으로 이동하고, 휴지통에 있던 메일은 영구 삭제했습니다.",
  },
  "delete-permanent": {
    tone: "success",
    message: "선택한 메일을 영구 삭제했습니다.",
  },
  "move-spam": {
    tone: "success",
    message: "선택한 발송자의 모든 메일을 스팸함으로 이동했습니다.",
  },
  "move-folder": {
    tone: "success",
    message: "선택한 메일을 폴더로 이동했습니다.",
  },
  "sender-spam": {
    tone: "success",
    message: "해당 발송자를 스팸 자동 분류 대상으로 등록하고 기존 메일을 스팸함으로 이동했습니다.",
  },
  "sender-unspam": {
    tone: "success",
    message: "해당 발송자를 스팸 자동 분류 대상에서 해제했습니다.",
  },
  "sender-unspam-moved": {
    tone: "success",
    message: "해당 발송자를 스팸 자동 분류 대상에서 해제하고 기존 메일을 선택한 메일함으로 이동했습니다.",
  },
  "move-sent-only": {
    tone: "error",
    message: "보낸 메일만 보낸메일함으로 이동할 수 있습니다.",
  },
  "move-conflict": {
    tone: "error",
    message: "메일함 상태가 최신이 아니어서 이동에 실패했습니다. 메일함을 다시 동기화한 뒤 다시 시도해주세요.",
  },
  "folder-name-required": {
    tone: "error",
    message: "새 메일함 이름을 입력해주세요.",
  },
  "folder-name-exists": {
    tone: "error",
    message: "같은 이름의 메일함이 이미 있습니다.",
  },
  "mailbox-connected": {
    tone: "success",
    message: "메일함 비밀번호를 저장하고 실동기화를 완료했습니다.",
  },
  "compose-required": {
    tone: "error",
    message: "받는 사람(또는 참조/숨은참조), 제목, 본문 또는 첨부 파일을 입력해주세요.",
  },
  "free-send-limit-daily": {
    tone: "error",
    message: "무료 플랜 대표 계정은 하루 30건까지 메일을 보낼 수 있습니다.",
  },
  "invalid-recipient": {
    tone: "error",
    message: "받는 사람, 참조, 숨은참조에는 올바른 이메일 주소만 입력할 수 있습니다.",
  },
  "mailbox-connection-failed": {
    tone: "error",
    message: "메일함 연결 검증에 실패했습니다.",
  },
  "mailbox-password-required": {
    tone: "error",
    message: "메일함 비밀번호를 입력해주세요.",
  },
  "ai-assist-config-missing": {
    tone: "error",
    message: "AI 어시스트 시스템 메일 설정이 비어 있습니다.",
  },
  "ai-assist-invalid-email": {
    tone: "error",
    message: "알림 수신 주소에는 올바른 이메일만 입력할 수 있습니다.",
  },
  "ai-assist-notification-required": {
    tone: "error",
    message: "AI 알림을 받을 이메일 주소를 입력해주세요.",
  },
  "ai-assist-plan-required": {
    tone: "error",
    message: "AI 어시스트는 성장 플랜에서만 사용할 수 있습니다. 결제 및 구독에서 성장 플랜을 시작해주세요.",
  },
  "member-required": {
    tone: "error",
    message: "멤버 이름, 메일 아이디, 비밀번호를 모두 입력해주세요.",
  },
  "member-password-mismatch": {
    tone: "error",
    message: "멤버 메일함 비밀번호와 확인 값이 서로 다릅니다.",
  },
  "member-mailbox-taken": {
    tone: "error",
    message: "이미 사용 중인 멤버 메일 주소입니다.",
  },
  "member-not-found": {
    tone: "error",
    message: "대상 멤버 메일함을 찾을 수 없습니다.",
  },
  "member-management-forbidden": {
    tone: "error",
    message: "멤버 관리는 대표 관리자 계정에서만 접근할 수 있습니다.",
  },
  "member-plan-required": {
    tone: "error",
    message: "팀 멤버 추가는 성장플랜 구독 중일 때 가능합니다.",
  },
  "member-billing-inactive": {
    tone: "error",
    message: "결제수단이 활성 상태가 아니어서 멤버 추가 결제를 진행할 수 없습니다.",
  },
  "member-charge-failed": {
    tone: "error",
    message: "멤버 추가 3,900원 결제 인증에 실패했습니다. 결제수단 상태를 확인해주세요.",
  },
  "member-create-refunded": {
    tone: "error",
    message: "멤버 생성 중 오류가 발생해 방금 결제는 자동으로 취소했습니다.",
  },
  "member-charge-refund-failed": {
    tone: "error",
    message:
      "멤버 생성은 실패했습니다. 결제 취소가 자동 완료되지 않았으므로 결제내역을 바로 확인해주세요.",
  },
  "compose-failed": {
    tone: "error",
    message: "메일 처리 중 오류가 발생했습니다.",
  },
  "imap-failed": {
    tone: "error",
    message: "IMAP 동기화 중 오류가 발생했습니다.",
  },
  "mailbox-auth": {
    tone: "error",
    message: "메일함 인증 정보가 없거나 올바르지 않습니다.",
  },
  "send-cooldown-active": {
    tone: "error",
    message: "짧은 시간 안에 많은 메일이 감지되어 메일 발송이 5분 동안 일시 중단되었습니다.",
  },
  "refresh-failed": {
    tone: "error",
    message: "메일함 새로고침 중 오류가 발생했습니다.",
  },
  "read-failed": {
    tone: "error",
    message: "읽음 상태 변경 중 오류가 발생했습니다.",
  },
  "star-failed": {
    tone: "error",
    message: "중요 표시 변경 중 오류가 발생했습니다.",
  },
  "move-failed": {
    tone: "error",
    message: "메일 이동 중 오류가 발생했습니다.",
  },
  "billing-registration-returned": {
    tone: "success",
    message: "결제수단 등록을 마쳤습니다. 잠시 후 상태가 반영되면 바로 사용할 수 있습니다.",
  },
  "billing-registration-failed": {
    tone: "error",
    message: "토스 앱 자동결제 등록이 취소되었거나 실패했습니다.",
  },
  "billing-management-forbidden": {
    tone: "error",
    message: "플랜 변경과 결제 관리는 각 도메인의 대표 관리자 계정에서만 가능합니다.",
  },
  "sender-spam-failed": {
    tone: "error",
    message: "발송자 스팸 설정 처리 중 오류가 발생했습니다.",
  },
  "smtp-failed": {
    tone: "error",
    message: "SMTP 발송 중 오류가 발생했습니다.",
  },
  system: {
    tone: "error",
    message: "처리 중 오류가 발생했습니다.",
  },
};

const setupSections: MailSetupSection[] = [
  "account",
  "domain",
  "assistant",
  "members",
  "billing",
];

export default async function MailPage({ searchParams }: MailPageProps) {
  const user = await requireSessionUser();
  const params = searchParams ? await searchParams : {};
  const folder = pickParam(params.folder) ?? "inbox";
  const panel = pickParam(params.panel);
  const sectionParam = pickParam(params.section);
  const normalizedSectionParam =
    sectionParam === "security"
      ? "account"
      : sectionParam === "addresses"
        ? "members"
        : sectionParam;
  const view = pickParam(params.view) === "compose" ? "compose" : "list";
  const page = pickPositivePage(params.page);
  const pageSize = normalizeMailboxPageSize(pickParam(params.pageSize));
  const messageFilter = pickMessageFilter(params.tab);
  const searchField = pickSearchField(params.field);
  const searchQuery = pickParam(params.q)?.trim() ?? "";
  const composeSelf = pickParam(params.self) === "1";
  const composeTo = pickParam(params.to) ?? "";
  const composeCc = pickParam(params.cc) ?? "";
  const composeBcc = pickParam(params.bcc) ?? "";
  const composeSubject = pickParam(params.subject) ?? "";
  const composeBody = pickParam(params.body) ?? "";
  const composeBodyHtml = pickParam(params.bodyHtml) ?? "";
  const composeMode = pickComposeMode(params.composeMode);
  const detailParam = pickParam(params.detail);
  const detailView =
    detailParam === "source" || detailParam === "logs" ? detailParam : "body";
  const billingTab = pickMailBillingTab(params.billingTab);
  const billingHistoryState = resolveMailBillingHistoryState({
    from: pickParam(params.billingFrom),
    page: pickMailBillingHistoryPage(params.billingPage),
    rangePreset: pickMailBillingHistoryRangePreset(params.billingRange),
    to: pickParam(params.billingTo),
  });
  const memberMailboxId = pickPositiveInteger(params.memberMailbox);
  const memberMailboxFolder = pickParam(params.memberFolder) ?? "inbox";
  const memberMailboxPage = pickPositivePage(params.memberPage);
  const memberMailboxMessageId = pickPositiveInteger(params.memberMessage);
  const details = pickParam(params.details);
  const messageParam = pickParam(params.message);
  const messageId = messageParam ? Number(messageParam) : null;
  const success = pickParam(params.success);
  const error = pickParam(params.error);
  const baseNotice = success ? noticeMap[success] : error ? noticeMap[error] : null;
  const currentPanel =
    !user.mailConfigured
      ? "setup"
      : panel === "setup"
        ? "setup"
        : panel === "auto-send"
          ? "auto-send"
          : "mail";
  const setupSection =
    normalizedSectionParam && setupSections.includes(normalizedSectionParam as MailSetupSection)
      ? (normalizedSectionParam as MailSetupSection)
      : "domain";
  const billingOwnership = await getMailBillingOwnershipByEmail(user.email);
  const canManageBilling = billingOwnership.canManageBilling;
  const billingOwnerEmail = billingOwnership.ownerEmail;

  if (
    currentPanel === "setup" &&
    !canManageBilling &&
    (setupSection === "domain" || setupSection === "members" || setupSection === "billing")
  ) {
    redirect(user.mailConfigured ? "/mail?folder=all" : "/mail?panel=setup&section=account");
  }

  if (currentPanel === "mail" && view !== "compose") {
    // Mail sync can stall on remote IMAP. Schedule it after the response so
    // inbox navigation renders cached data immediately instead of blocking.
    after(async () => {
      try {
        await refreshMailboxIfStaleByEmail(user.email, { folder });
      } catch {
        // Keep rendering cached mailbox data even if the background sync fails.
      }
    });
  }

  const storedLayoutPreferences = await getMailLayoutPreferencesByEmail(user.email);
  const layoutPreferences = {
    ...storedLayoutPreferences,
    sortOrder: pickSortOrder(params.sort, storedLayoutPreferences.sortOrder),
  };

  const [mailData, setupOverview] = await Promise.all([
    currentPanel === "mail" || user.mailConfigured
      ? getMailAppOverviewByEmail(user.email, {
          folder,
          messageId: Number.isFinite(messageId) ? messageId : null,
          messageFilter,
          sortOrder: layoutPreferences.sortOrder,
          searchField,
          searchQuery,
          page,
          pageSize,
          markMessageRead:
            currentPanel === "mail" && view !== "compose" && Number.isFinite(messageId),
        })
      : Promise.resolve(null),
    getMailSetupOverviewByEmail(user.email),
  ]);
  let managedMembers: ManagedMailboxMember[] = [];
  let aiAssistOverview: MailAiAssistOverview | null = null;
  let autoSendOverview: MailAutoSendOverview | null = null;
  let billingOverview: MailBillingOverview | null = null;
  let billingCancellationOverview: MailBillingCancellationOverview | null = null;
  let billingHistoryPage: MailBillingHistoryPage | null = null;
  let memberMailboxView: MemberMailboxViewState | null = null;

  if (setupOverview) {
    const [
      membersResult,
      aiAssistResult,
      autoSendResult,
      billingResult,
      billingCancellationResult,
      billingHistoryResult,
    ] = await Promise.all([
      getManagedMembersByOwnerEmail(billingOwnerEmail).catch(() => []),
      getAiAssistOverviewByOwnerEmail(user.email).catch(() => null),
      getAutoSendOverviewByOwnerEmail(user.email).catch(() => null),
      getMailBillingOverviewByOwnerEmail(billingOwnerEmail, {
        recoverRemoteStatus: currentPanel === "setup" && setupSection === "billing",
      }).catch(() => null),
      currentPanel === "setup" && setupSection === "billing"
        ? getMailBillingCancellationOverviewByOwnerEmail(billingOwnerEmail).catch(() => null)
        : Promise.resolve(null),
      currentPanel === "setup" && setupSection === "billing" && billingTab === "history"
        ? getMailBillingHistoryByOwnerEmail(billingOwnerEmail, {
            from: billingHistoryState.from,
            page: billingHistoryState.page,
            rangePreset: billingHistoryState.rangePreset,
            to: billingHistoryState.to,
          }).catch(() => null)
        : Promise.resolve(null),
    ]);

    managedMembers = membersResult;
    aiAssistOverview = aiAssistResult;
    autoSendOverview = autoSendResult;
    billingOverview = billingResult;
    billingCancellationOverview = billingCancellationResult;
    billingHistoryPage = billingHistoryResult;
  }

  if (currentPanel === "setup" && setupSection === "members" && memberMailboxId !== null) {
    if (!canManageBilling) {
      redirect(user.mailConfigured ? "/mail?folder=all" : "/mail?panel=setup&section=account");
    }

    const selectedMember = managedMembers.find((member) => member.id === memberMailboxId) ?? null;

    if (!selectedMember) {
      redirect("/mail?panel=setup&section=members&error=member-not-found");
    }

    const selectedMemberMailboxData = await getMailAppOverviewByEmail(selectedMember.email, {
      folder: memberMailboxFolder,
      messageId: memberMailboxMessageId,
      page: memberMailboxPage,
      pageSize: 10,
      sortOrder: layoutPreferences.sortOrder,
    });

    memberMailboxView = {
      data: selectedMemberMailboxData,
      folder: memberMailboxFolder,
      member: selectedMember,
      messageId: memberMailboxMessageId,
      page: memberMailboxPage,
    };
  }

  const effectiveBillingHistoryState: MailBillingHistoryState = billingHistoryPage
    ? {
        from: billingHistoryPage.from,
        page: billingHistoryPage.page,
        rangePreset: billingHistoryPage.rangePreset,
        to: billingHistoryPage.to,
      }
    : billingHistoryState;

  const notice =
    baseNotice && details
      ? { ...baseNotice, message: `${baseNotice.message} (${details})` }
      : baseNotice;
  const sourceComposeDefaults = resolveSourceComposeDefaults({
    bcc: composeBcc,
    body: composeBody,
    bodyHtml: composeBodyHtml,
    cc: composeCc,
    message: view === "compose" ? mailData?.selectedMessage ?? null : null,
    mode: composeMode,
    ownAddresses: [user.email, user.mailbox].filter(Boolean),
    subject: composeSubject,
    to: composeSelf ? user.email : composeTo,
  });
  const sanitizedComposeBodyHtml =
    sanitizeMailboxHtml(sourceComposeDefaults.bodyHtml) ??
    (sourceComposeDefaults.body.trim() ? plainTextToHtml(sourceComposeDefaults.body) : "");
  const subscriptionStatus = billingOverview?.subscription?.status ?? null;
  const billingStatus =
    subscriptionStatus === "active" &&
    !billingOverview?.subscription?.initialPaymentComplete
      ? "pending"
      : subscriptionStatus;
  const planSummary = createMailPlanSummary({
    billingSeatCount: countMailBillingSeatsFromManagedMembers(
      managedMembers.length,
    ),
    billingStatus,
    isComplimentary: hasComplimentaryGrowthPlanByEmail(billingOwnerEmail),
  });

  return (
    <div className="mail-workspace min-h-screen bg-[#f6f7fb]">
      <main className="h-screen w-full overflow-hidden">
        <MailGate
          key={[
            currentPanel,
            folder,
            view,
            composeMode,
            detailView,
            messageParam ?? "",
            page,
            messageFilter,
            searchField,
            searchQuery,
            layoutPreferences.viewMode,
            layoutPreferences.sortOrder,
            sourceComposeDefaults.to,
            sourceComposeDefaults.cc,
            sourceComposeDefaults.bcc,
            sourceComposeDefaults.subject,
            sanitizedComposeBodyHtml.length,
            billingTab,
            effectiveBillingHistoryState.page,
            effectiveBillingHistoryState.rangePreset,
            effectiveBillingHistoryState.from ?? "",
            effectiveBillingHistoryState.to ?? "",
            notice?.tone ?? "",
            notice?.message ?? "",
            mailData?.lastSyncAt ?? "",
            memberMailboxView?.member.id ?? "",
            memberMailboxView?.data?.currentFolder ?? "",
            memberMailboxView?.data?.currentPage ?? "",
            memberMailboxView?.data?.selectedMessage?.id ?? "",
          ].join(":")}
          currentPanel={currentPanel}
          setupSection={setupSection}
          setupOverview={setupOverview}
          managedMembers={managedMembers}
          memberMailboxView={memberMailboxView}
          aiAssistOverview={aiAssistOverview}
          autoSendOverview={autoSendOverview}
          billingOverview={billingOverview}
          billingCancellationOverview={billingCancellationOverview}
          billingTab={billingTab}
          billingHistoryPage={billingHistoryPage}
          billingHistoryState={effectiveBillingHistoryState}
          planSummary={planSummary}
          canManageBilling={canManageBilling}
          mailConfigured={user.mailConfigured}
          userEmail={user.email}
          userDisplayName={user.displayName}
          mailbox={user.mailbox}
          companyName={user.companyName}
          domain={user.domain}
          data={mailData}
          currentFolder={mailData?.currentFolder ?? folder}
          currentView={view}
          composeMode={composeMode}
          detailView={detailView}
          detailOpen={view === "compose" || Boolean(messageParam)}
          currentSearchField={searchField}
          currentSearchQuery={searchQuery}
          composeBccDefault={sourceComposeDefaults.bcc}
          composeCcDefault={sourceComposeDefaults.cc}
          composeToDefault={sourceComposeDefaults.to}
          composeSubjectDefault={sourceComposeDefaults.subject}
          composeBodyDefault={sourceComposeDefaults.body}
          composeBodyHtmlDefault={sanitizedComposeBodyHtml}
          layoutPreferences={layoutPreferences}
          notice={notice}
        />
      </main>
    </div>
  );
}
