package ru.forbion.f7cloud.feature.mail

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.ui.Modifier
import ru.forbion.f7cloud.core.auth.AuthSession
import ru.forbion.f7cloud.core.designsystem.F7Theme
import ru.forbion.f7cloud.feature.contacts.ContactsRepository

class MailComposeActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val launch = readLaunch() ?: run {
            finish()
            return
        }
        val session = AuthSession(
            serverUrl = launch.serverUrl,
            username = launch.username,
            appPassword = launch.password,
            trustAllCerts = launch.trustAllCerts,
        )
        val vm = MailComposeViewModel(
            launch = launch,
            contactsRepository = ContactsRepository(applicationContext),
        )
        setContent {
            F7Theme {
                MailComposeScreen(
                    session = session,
                    launch = launch,
                    vm = vm,
                    onClose = { finish() },
                    onUnauthorized = { finish() },
                    modifier = Modifier.fillMaxSize(),
                )
            }
        }
    }

    private fun readLaunch(): MailComposeLaunch? {
        val username = intent.getStringExtra(EXTRA_USERNAME).orEmpty()
        val serverUrl = intent.getStringExtra(EXTRA_SERVER_URL).orEmpty()
        val accountId = intent.getIntExtra(EXTRA_ACCOUNT_ID, 0)
        val accountEmail = intent.getStringExtra(EXTRA_ACCOUNT_EMAIL).orEmpty()
        if (username.isBlank() || serverUrl.isBlank() || accountId <= 0 || accountEmail.isBlank()) {
            return null
        }
        return MailComposeLaunch(
            username = username,
            password = intent.getStringExtra(EXTRA_PASSWORD).orEmpty(),
            serverUrl = serverUrl,
            trustAllCerts = intent.getBooleanExtra(EXTRA_TRUST_ALL_CERTS, false),
            accountId = accountId,
            accountEmail = accountEmail,
            accountName = intent.getStringExtra(EXTRA_ACCOUNT_NAME),
            mailboxId = intent.getIntExtra(EXTRA_MAILBOX_ID, 0).takeIf { it > 0 },
            mode = runCatching {
                MailComposeMode.valueOf(intent.getStringExtra(EXTRA_MODE) ?: MailComposeMode.NEW.name)
            }.getOrDefault(MailComposeMode.NEW),
            initialTo = intent.getStringExtra(EXTRA_INITIAL_TO).orEmpty(),
            initialCc = intent.getStringExtra(EXTRA_INITIAL_CC).orEmpty(),
            initialSubject = intent.getStringExtra(EXTRA_INITIAL_SUBJECT).orEmpty(),
            initialBodyHtml = intent.getStringExtra(EXTRA_INITIAL_BODY_HTML).orEmpty(),
            showCcBcc = intent.getBooleanExtra(EXTRA_SHOW_CC_BCC, false),
            initialSendPreset = runCatching {
                MailSendLaterPreset.valueOf(
                    intent.getStringExtra(EXTRA_INITIAL_SEND_PRESET) ?: MailSendLaterPreset.NOW.name,
                )
            }.getOrDefault(MailSendLaterPreset.NOW),
            initialCustomSendAtEpochSeconds = intent.getLongExtra(EXTRA_INITIAL_CUSTOM_SEND_AT, 0L)
                .takeIf { it > 0L },
        )
    }

    companion object {
        private const val EXTRA_USERNAME = "username"
        private const val EXTRA_PASSWORD = "password"
        private const val EXTRA_SERVER_URL = "server_url"
        private const val EXTRA_TRUST_ALL_CERTS = "trust_all_certs"
        private const val EXTRA_ACCOUNT_ID = "account_id"
        private const val EXTRA_ACCOUNT_EMAIL = "account_email"
        private const val EXTRA_ACCOUNT_NAME = "account_name"
        private const val EXTRA_MAILBOX_ID = "mailbox_id"
        private const val EXTRA_MODE = "compose_mode"
        private const val EXTRA_INITIAL_TO = "initial_to"
        private const val EXTRA_INITIAL_CC = "initial_cc"
        private const val EXTRA_INITIAL_SUBJECT = "initial_subject"
        private const val EXTRA_INITIAL_BODY_HTML = "initial_body_html"
        private const val EXTRA_SHOW_CC_BCC = "show_cc_bcc"
        private const val EXTRA_INITIAL_SEND_PRESET = "initial_send_preset"
        private const val EXTRA_INITIAL_CUSTOM_SEND_AT = "initial_custom_send_at"

        fun intent(context: Context, launch: MailComposeLaunch): Intent =
            Intent(context, MailComposeActivity::class.java).apply {
                putExtra(EXTRA_USERNAME, launch.username)
                putExtra(EXTRA_PASSWORD, launch.password)
                putExtra(EXTRA_SERVER_URL, launch.serverUrl)
                putExtra(EXTRA_TRUST_ALL_CERTS, launch.trustAllCerts)
                putExtra(EXTRA_ACCOUNT_ID, launch.accountId)
                putExtra(EXTRA_ACCOUNT_EMAIL, launch.accountEmail)
                putExtra(EXTRA_ACCOUNT_NAME, launch.accountName)
                launch.mailboxId?.let { putExtra(EXTRA_MAILBOX_ID, it) }
                putExtra(EXTRA_MODE, launch.mode.name)
                putExtra(EXTRA_INITIAL_TO, launch.initialTo)
                putExtra(EXTRA_INITIAL_CC, launch.initialCc)
                putExtra(EXTRA_INITIAL_SUBJECT, launch.initialSubject)
                putExtra(EXTRA_INITIAL_BODY_HTML, launch.initialBodyHtml)
                putExtra(EXTRA_SHOW_CC_BCC, launch.showCcBcc)
                putExtra(EXTRA_INITIAL_SEND_PRESET, launch.initialSendPreset.name)
                launch.initialCustomSendAtEpochSeconds?.let { putExtra(EXTRA_INITIAL_CUSTOM_SEND_AT, it) }
            }

        fun launch(context: Context, session: AuthSession, accountId: Int, accountEmail: String, mailboxId: Int? = null) {
            context.startActivity(
                intent(
                    context,
                    MailComposeLaunch(
                        username = session.username,
                        password = session.appPassword,
                        serverUrl = session.serverUrl,
                        trustAllCerts = session.trustAllCerts,
                        accountId = accountId,
                        accountEmail = accountEmail,
                        mailboxId = mailboxId,
                    ),
                ),
            )
        }
    }
}
