package chat.vojo.proxy

import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.VpnService
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.SystemBarStyle
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import chat.vojo.proxy.service.ProxyVpnService
import chat.vojo.proxy.service.VpnState
import chat.vojo.proxy.ui.MainScreen
import chat.vojo.proxy.ui.MainViewModel
import chat.vojo.proxy.ui.theme.VojoTheme

class MainActivity : ComponentActivity() {

    private val viewModel: MainViewModel by viewModels()
    private var pendingConnect = false

    private val vpnPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == RESULT_OK) {
            ProxyVpnService.start(this)
        } else {
            // Make the refusal visible instead of silently doing nothing.
            VpnState.setStopped("Доступ к VPN не разрешён")
        }
    }

    private val notificationPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) {
        // Best-effort; the tunnel works without it.
        if (pendingConnect) {
            pendingConnect = false
            launchVpnFlow()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // The app is dark-only: force light icons even on a light system theme.
        enableEdgeToEdge(
            statusBarStyle = SystemBarStyle.dark(Color.TRANSPARENT),
            navigationBarStyle = SystemBarStyle.dark(Color.TRANSPARENT),
        )

        setContent {
            VojoTheme {
                MainScreen(
                    vm = viewModel,
                    onConnect = ::requestConnect,
                    onDisconnect = { ProxyVpnService.stop(this) },
                    onReconnect = { viewModel.reconnect() },
                )
            }
        }
    }

    /**
     * Asks for POST_NOTIFICATIONS in context — right before the first connect,
     * when the user understands why the tunnel notification matters.
     */
    private fun requestConnect() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            val granted = ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==
                PackageManager.PERMISSION_GRANTED
            if (!granted) {
                pendingConnect = true
                notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
                return
            }
        }
        launchVpnFlow()
    }

    private fun launchVpnFlow() {
        val prepare = VpnService.prepare(this)
        if (prepare != null) {
            vpnPermissionLauncher.launch(prepare)
        } else {
            ProxyVpnService.start(this)
        }
    }
}
