package ru.forbion.f7cloud.mobile

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.fragment.app.FragmentActivity
import ru.forbion.f7cloud.core.auth.AuthStore
import ru.forbion.f7cloud.core.push.F7PushIntentExtras
import ru.forbion.f7cloud.core.push.PushIntents
import ru.forbion.f7cloud.feature.talk.TalkHelper
import ru.forbion.f7cloud.feature.talknative.TalkNativeCallLauncher
import ru.forbion.f7cloud.mobile.permissions.F7AppPermissions
import ru.forbion.f7cloud.mobile.ui.AppScaffold

class MainActivity : FragmentActivity() {
    private var openUrl by mutableStateOf<String?>(null)

    private val runtimePermissionsLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions(),
    ) { results ->
        Log.d(TAG, "Runtime permissions result: $results")
        onPermissionsResult?.invoke()
        onPermissionsResult = null
    }

    /** Вызывается после системного диалога разрешений (для регистрации FCM и т.д.). */
    var onPermissionsResult: (() -> Unit)? = null

    fun launchMissingRuntimePermissions(onFinished: (() -> Unit)? = null) {
        val missing = F7AppPermissions.missing(this)
        if (missing.isEmpty()) {
            onFinished?.invoke()
            return
        }
        onPermissionsResult = onFinished
        runtimePermissionsLauncher.launch(missing.toTypedArray())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        // Системный сплэш (фон + иконка) на холодном старте вместо белого экрана
        installSplashScreen()
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        if (!handleIncomingIntent(intent)) {
            openUrl = resolveOpenUrl(intent)
        }
        setContent {
            AppScaffold(
                openUrl = openUrl,
                onOpenUrlConsumed = { openUrl = null },
                onRequestRuntimePermissions = { finished ->
                    launchMissingRuntimePermissions(finished)
                },
            )
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        if (!handleIncomingIntent(intent)) {
            openUrl = resolveOpenUrl(intent)
        }
    }

    private fun resolveOpenUrl(intent: Intent?): String? {
        if (intent == null) return null
        if (F7PushIntentExtras.isFcmLaunch(intent)) {
            F7PushIntentExtras.publishEventFromIntent(intent)
        }
        if (intent.data?.toString() == "f7cloud://talk") {
            val session = AuthStore(this).load() ?: return null
            return "${session.serverUrl.trimEnd('/')}/apps/spreed/"
        }
        val url = F7PushIntentExtras.resolveOpenUrl(intent)
        val room = F7PushIntentExtras.resolveRoomToken(intent)
        val messageId = F7PushIntentExtras.resolveMessageId(intent)
        if (!url.isNullOrBlank()) {
            if (!messageId.isNullOrBlank() && !url.contains("#message_")) {
                return "$url#message_$messageId"
            }
            return url
        }
        if (!room.isNullOrBlank()) {
            val session = AuthStore(this).load() ?: return null
            val base = "${session.serverUrl.trimEnd('/')}/index.php/apps/spreed/$room"
            return if (!messageId.isNullOrBlank()) "$base#message_$messageId" else base
        }
        return null
    }

    /** @return true if intent was fully handled (call launched). */
    private fun handleIncomingIntent(intent: Intent?): Boolean {
        if (intent == null) return false
        val session = AuthStore(this).load()
        when {
            intent.action == PushIntents.ACTION_OPEN_CALL -> {
                val acceptUrl = intent.getStringExtra(PushIntents.EXTRA_ACCEPT_URL)
                if (!acceptUrl.isNullOrBlank() && session != null) {
                    if (intent.getBooleanExtra(PushIntents.EXTRA_AUTO_ACCEPT, false)) {
                        TalkNativeCallLauncher.launchIncomingCall(this, session, acceptUrl)
                    } else {
                        startActivity(
                            Intent(intent).apply {
                                setClass(this@MainActivity, CallIncomingActivity::class.java)
                                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                            },
                        )
                    }
                    return true
                }
            }
            else -> {
                val url = intent.getStringExtra(PushIntents.EXTRA_OPEN_URL)
                if (!url.isNullOrBlank() && TalkHelper.isCallRoomUrl(url) && session != null) {
                    TalkNativeCallLauncher.launchIncomingCall(this, session, url)
                    return true
                }
            }
        }
        return false
    }

    companion object {
        private const val TAG = "MainActivity"
    }
}
