import { notFound } from "next/navigation";
import { requireSessionUser } from "@/lib/auth";
import { getMailboxMessageBodyViewByEmail } from "@/lib/official-mail";

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

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

function formatSize(bytes: number) {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

function hasVisibleBody(html: string, text: string) {
  if (text.trim()) return true;

  const visibleHtmlText = html
    .replace(/<[^>]*>/g, "")
    .replace(/&(?:nbsp|#160|#xA0);/gi, "")
    .trim();

  return Boolean(visibleHtmlText) || /<(?:img|svg|video|audio|table|hr)\b/i.test(html);
}

export default async function MailMessageBodyPage({
  searchParams,
}: MailMessageBodyPageProps) {
  const user = await requireSessionUser();
  const params = searchParams ? await searchParams : {};
  const messageId = Number(pickParam(params.message));

  if (!Number.isInteger(messageId) || messageId <= 0) {
    notFound();
  }

  const message = await getMailboxMessageBodyViewByEmail(user.email, messageId);

  if (!message) {
    notFound();
  }

  const html = message.bodyHtmlDisplay?.trim() ?? "";
  const showBody = hasVisibleBody(html, message.bodyText);
  const attachments = message.attachments.filter((attachment) => !attachment.isInline);
  const sender = message.fromName?.trim()
    ? `${message.fromName.trim()} <${message.fromAddress}>`
    : message.fromAddress;
  const receivedAt = new Intl.DateTimeFormat("ko-KR", {
    dateStyle: "medium",
    timeStyle: "short",
    timeZone: "Asia/Seoul",
  }).format(new Date(message.receivedAt));

  return (
    <main className="flex h-dvh min-h-[400px] flex-col overflow-hidden bg-white text-[#1f2c45]">
      <header className="shrink-0 border-b border-[#e5ebf4] px-5 py-5 sm:px-8">
        <div className="flex flex-wrap items-start justify-between gap-3">
          <h1 className="min-w-0 break-words text-[20px] font-semibold leading-7 text-[#16233c]">
            {message.subject.trim() || "(제목 없음)"}
          </h1>
          <a
            href={`/mail?folder=all&message=${messageId}&detail=body`}
            className="shrink-0 text-[12px] font-semibold text-[#2f6df6] hover:underline"
          >
            메일함에서 보기
          </a>
        </div>
        <dl className="mt-4 grid gap-x-4 gap-y-1.5 text-[13px] leading-5 sm:grid-cols-[72px_minmax(0,1fr)]">
          <dt className="text-[#7a879c]">보낸사람</dt>
          <dd className="min-w-0 break-all">{sender}</dd>
          <dt className="text-[#7a879c]">받는사람</dt>
          <dd className="min-w-0 break-all">{message.toAddresses}</dd>
          <dt className="text-[#7a879c]">받은시간</dt>
          <dd>{receivedAt}</dd>
        </dl>
      </header>

      {attachments.length > 0 ? (
        <section aria-label="첨부파일" className="max-h-[35dvh] shrink-0 overflow-y-auto border-b border-[#e5ebf4] px-5 py-4 sm:px-8">
          <h2 className="text-[13px] font-semibold text-[#23324b]">첨부파일 {attachments.length}개</h2>
          <ul className="mt-3 divide-y divide-[#e9eef6] rounded-[10px] border border-[#e0e7f1]">
            {attachments.map((attachment) => {
              const href = attachment.isLargeAttachment
                ? attachment.externalUrl
                : `/api/mailbox/attachment?message=${messageId}&index=${attachment.index}&mode=download`;

              return (
                <li key={`${attachment.index}-${attachment.filename}`} className="flex flex-wrap items-center gap-x-2 gap-y-1 px-3 py-2.5 text-[12px]">
                  {href && !attachment.isPendingPublication ? (
                    <a href={href} className="min-w-0 break-all font-medium text-[#2f6df6] hover:underline" rel="noopener noreferrer">
                      {attachment.filename}
                    </a>
                  ) : (
                    <span className="min-w-0 break-all font-medium text-[#667792]">{attachment.filename}</span>
                  )}
                  {attachment.isLargeAttachment ? <span className="rounded bg-[#eef4ff] px-1.5 py-0.5 text-[10px] font-semibold text-[#2f6df6]">대용량</span> : null}
                  <span className="text-[#8794a8]">{formatSize(attachment.sizeBytes)}</span>
                </li>
              );
            })}
          </ul>
        </section>
      ) : null}

      <section aria-label="메일 본문" className="flex min-h-0 flex-1 flex-col overflow-y-auto">
        {showBody ? (
          html ? (
            <iframe
              title={message.subject.trim() || "메일 본문"}
              src={`/api/mailbox/message-document?message=${messageId}&view=popup`}
              sandbox="allow-popups allow-popups-to-escape-sandbox allow-same-origin"
              referrerPolicy="no-referrer"
              className="block min-h-0 w-full flex-1 border-0 bg-white"
            />
          ) : (
            <pre className="whitespace-pre-wrap break-words bg-white px-5 py-6 text-[15px] leading-7 sm:px-8">
              {message.bodyText}
            </pre>
          )
        ) : (
          <p className="px-5 py-10 text-[13px] text-[#8794a8] sm:px-8">본문 내용이 없습니다.</p>
        )}
      </section>
    </main>
  );
}
