package ru.forbion.f7cloud.feature.mail

object MailReplyHelper {
    fun extractEmail(raw: String): String {
        if (raw.isBlank()) return ""
        val match = Regex("<([^>]+)>").find(raw)
        return match?.groupValues?.get(1)?.trim() ?: raw.trim()
    }

    fun replySubject(subject: String): String {
        val trimmed = subject.trim().ifBlank { "(без темы)" }
        return if (trimmed.startsWith("Re:", ignoreCase = true)) trimmed else "Re: $trimmed"
    }

    fun forwardSubject(subject: String): String {
        val trimmed = subject.trim().ifBlank { "(без темы)" }
        return when {
            trimmed.startsWith("Fwd:", ignoreCase = true) -> trimmed
            trimmed.startsWith("Fw:", ignoreCase = true) -> trimmed
            else -> "Fwd: $trimmed"
        }
    }

    fun buildComposeLaunch(
        base: MailComposeLaunch,
        detail: MailMessageDetail,
        mode: MailComposeMode,
        accountEmail: String,
    ): MailComposeLaunch {
        val senderEmail = extractEmail(detail.from)
        val senderLabel = detail.from.ifBlank { senderEmail }.ifBlank { "Неизвестный" }
        val quotedBody = buildQuotedBodyHtml(detail, mode)

        return when (mode) {
            MailComposeMode.REPLY -> base.copy(
                mode = mode,
                initialTo = formatRecipient(senderLabel, senderEmail),
                initialSubject = replySubject(detail.subject),
                initialBodyHtml = quotedBody,
                showCcBcc = false,
            )
            MailComposeMode.REPLY_ALL -> {
                val cc = buildReplyAllCc(detail, accountEmail, senderEmail)
                base.copy(
                    mode = mode,
                    initialTo = formatRecipient(senderLabel, senderEmail),
                    initialCc = cc,
                    initialSubject = replySubject(detail.subject),
                    initialBodyHtml = quotedBody,
                    showCcBcc = cc.isNotBlank(),
                )
            }
            MailComposeMode.FORWARD -> base.copy(
                mode = mode,
                initialSubject = forwardSubject(detail.subject),
                initialBodyHtml = quotedBody,
                showCcBcc = false,
            )
            MailComposeMode.NEW -> base
        }
    }

    private fun formatRecipient(label: String, email: String): String {
        if (email.isBlank()) return label
        if (label.isBlank() || label.equals(email, ignoreCase = true)) return email
        return "$label <$email>"
    }

    private fun buildReplyAllCc(
        detail: MailMessageDetail,
        accountEmail: String,
        senderEmail: String,
    ): String {
        val own = accountEmail.lowercase()
        val sender = senderEmail.lowercase()
        return (detail.to + "," + detail.cc)
            .split(',', ';')
            .map { token -> extractEmail(token.trim()).ifBlank { token.trim() } }
            .filter { email ->
                email.isNotBlank() &&
                    !email.equals(own, ignoreCase = true) &&
                    !email.equals(sender, ignoreCase = true)
            }
            .distinct()
            .joinToString(", ")
    }

    private fun buildQuotedBodyHtml(detail: MailMessageDetail, mode: MailComposeMode): String {
        val body = if (detail.hasHtmlBody && detail.bodyHtml.isNotBlank()) {
            MailBodyHtml.normalizeForDisplay(detail.bodyHtml)
        } else {
            val plain = MailBodyHtml.normalizePlainForDisplay(
                detail.bodyPlain.ifBlank { detail.bodyHtml },
            )
            plain.replace("\n", "<br>")
        }
        val date = formatMessageDate(detail.dateInt)
        val from = detail.from.ifBlank { "Неизвестный" }
        val header = if (mode == MailComposeMode.FORWARD) {
            """
            <p>-------- Пересылаемое сообщение --------</p>
            <p><b>От:</b> ${escapeHtml(from)}</p>
            <p><b>Дата:</b> ${escapeHtml(date)}</p>
            <p><b>Тема:</b> ${escapeHtml(detail.subject)}</p>
            <p><b>Кому:</b> ${escapeHtml(detail.to)}</p>
            """.trimIndent()
        } else {
            """
            <p>${escapeHtml(date)}, ${escapeHtml(from)} писал(а):</p>
            """.trimIndent()
        }
        return "<br><br><blockquote class=\"quote\">$header$body</blockquote>"
    }

    private fun escapeHtml(text: String): String =
        text
            .replace("&", "&amp;")
            .replace("<", "&lt;")
            .replace(">", "&gt;")
            .replace("\"", "&quot;")
}
