package com.zaojiao.app.core.auth.ui

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.zaojiao.app.core.auth.model.TokenModel
import dagger.hilt.android.AndroidEntryPoint

private val LocalTokenSave = compositionLocalOf<((token: TokenModel?) -> Unit)?> { null }

@AndroidEntryPoint
class LoginActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            val navController = rememberNavController()

            CompositionLocalProvider(
                LocalTokenSave provides {
                    TokenActivity.start(this@LoginActivity, it?.accessToken, it?.refreshToken)
                    finish()
                }
            ) {
                MaterialTheme {
                    NavHost(
                        navController = navController,
                        startDestination = "/",
                    ) {
                        composable("/") {
                            LoginPage()
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun LoginPage(
    loginViewModel: LoginViewModel = hiltViewModel(),
) {
    Column(
        modifier = Modifier
            .statusBarsPadding()
            .fillMaxSize(),
    ) {
        CloseButton()

        val callback = LocalTokenSave.current

        Box(
            modifier = Modifier
                .clickable {
                    callback?.invoke(null)
                }
                .background(color = Color.Green)
                .weight(1f)
                .fillMaxWidth()
        )
    }
}

@Composable
fun CloseButton() {
    Icon(
        imageVector = Icons.Filled.Close,
        contentDescription = "关闭按钮",
    )
}