package com.zaojiao.app

import android.content.Intent
import android.os.BatteryManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.WindowManager
import androidx.activity.compose.setContent
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.fragment.app.FragmentActivity
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import com.zaojiao.app.core.auth.data.AuthRepository
import com.zaojiao.app.core.auth.model.TokenModel
import com.zaojiao.app.core.auth.ui.LoginActivity
import com.zaojiao.app.core.auth.utils.AuthUtils
import com.zaojiao.app.core.auth.utils.ITokenRequest
import com.zaojiao.app.feat.design.BackgroundTheme
import com.zaojiao.app.feat.design.LocalBackgroundTheme
import com.zaojiao.app.feat.design.LocalOnFinishDispatcher
import com.zaojiao.app.ui.App
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger
import javax.inject.Inject

private val LightBackgroundTheme = BackgroundTheme(color = Color.White)

private val DarkBackgroundTheme = BackgroundTheme(color = Color.Black)

@AndroidEntryPoint
class MainActivity : FragmentActivity(), ITokenRequest, CoroutineScope by MainScope() {
    companion object {
        private val tokenFlag = 99
        private val requests = ConcurrentHashMap<Int, CompletableFuture<TokenModel?>>()
        private val nextRequestCode = AtomicInteger(0)
    }

    private lateinit var windowInsetsController: WindowInsetsControllerCompat

    @Inject
    public lateinit var authRepository: AuthRepository

    override fun onCreate(savedInstanceState: Bundle?) {
        AuthUtils.attach(this)
        super.onCreate(savedInstanceState)
        configureSystemBar()

        getSystemService(BatteryManager::class.java)

        launch {
            authRepository.state.collect {
                Log.e("MainActivity", "onCreate: $it")
            }
        }

        setContent {
            val systemUiController = rememberSystemUiController()

            val backgroundTheme = if (isSystemInDarkTheme()) {
                DarkBackgroundTheme
            } else {
                LightBackgroundTheme
            }

            CompositionLocalProvider(
                LocalBackgroundTheme provides backgroundTheme,
                LocalOnFinishDispatcher provides { finish() }
            ) {
                MaterialTheme { App() }
            }
        }
    }

    private fun configureSystemBar() {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        windowInsetsController = WindowInsetsControllerCompat(window, window.decorView)

        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = android.graphics.Color.TRANSPARENT
        window.navigationBarColor = android.graphics.Color.TRANSPARENT

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            window.addFlags(WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES)
        }
        windowInsetsController.apply {
            show(WindowInsetsCompat.Type.systemBars())
        }
    }

    override fun onDestroy() {
        AuthUtils.detach()
        this.cancel()
        super.onDestroy()
    }

    override fun requestToken(): CompletableFuture<TokenModel?> {
        val requestCode = nextRequestCode.getAndIncrement()
        val tokenRequestCode = requestCode + tokenFlag shl 10
        val future = CompletableFuture<TokenModel?>()
        requests[tokenRequestCode] = future

        val intent = Intent(this, LoginActivity::class.java)
        startActivityForResult(intent, tokenRequestCode)
        return future
    }

    override fun requestLogin() {
        startActivity(Intent(this, LoginActivity::class.java))
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode shr 10 == tokenFlag) {
            when (resultCode) {
                RESULT_CANCELED -> {
                    requests[requestCode]!!.complete(null)
                }

                RESULT_OK -> {
                    requests[requestCode]!!.complete(
                        TokenModel(
                            accessToken = "1234",
                            refreshToken = "5678",
                        )
                    )
                }

                else -> {
                    requests[requestCode]!!.complete(null)
                }
            }
        }
    }
}