package com.example.initiateaphonecallapp

import android.Manifest
import android.app.AlertDialog
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.core.content.ContextCompat
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.initiateaphonecallapp.manager.CallRecordManager
import com.example.initiateaphonecallapp.manager.PreferenceManager
import com.example.initiateaphonecallapp.manager.StoragePermissionManager
import com.example.initiateaphonecallapp.ui.LoginSms.LoginSmsScreen
import com.example.initiateaphonecallapp.ui.MainScreen
import com.example.initiateaphonecallapp.ui.home.HomeScreen
import com.example.initiateaphonecallapp.ui.login.LoginScreen
import com.example.initiateaphonecallapp.ui.theme.InitiateAPhoneCallAppTheme

class MainActivity : ComponentActivity() {
    private val requiredPermissions = arrayOf(
        Manifest.permission.CALL_PHONE,
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.RECORD_AUDIO,
        Manifest.permission.POST_NOTIFICATIONS,
        Manifest.permission.READ_EXTERNAL_STORAGE,  // 添加文件搜索权限
        Manifest.permission.WRITE_EXTERNAL_STORAGE,   // 添加文件搜索权限
                Manifest.permission.MANAGE_EXTERNAL_STORAGE
    )
    // 在您的Composable函数中
    private fun showAllFilesAccessDialog() {
        AlertDialog.Builder(this)
            .setTitle("需要文件访问权限")
            .setMessage("为了访问通话录音文件，需要授予\"所有文件访问权限\"。请点击确定前往设置页面授权。")
            .setPositiveButton("确定") { _, _ ->
                storagePermissionManager.requestAllFilesAccess(this)
            }
            .setNegativeButton("取消") { _, _ ->
                // 即使用户拒绝，也继续初始化应用，但文件访问功能可能受限
            }
            .setCancelable(false)
            .show()
    }
    private lateinit var storagePermissionManager: StoragePermissionManager
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        CallRecordManager.initialize(this)
        println("🚀 Application: CallRecordManager 初始化完成")

        storagePermissionManager = StoragePermissionManager(this)

        // 检查所有文件访问权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
            !Environment.isExternalStorageManager()) {
            showAllFilesAccessDialog()
        }

        // 初始化 PreferenceManager
        PreferenceManager.initialize(this.applicationContext)
        // 检查并请求权限
        if (!hasAllPermissions()) {
            requestPermissions(requiredPermissions, PERMISSION_REQUEST_CODE)
        }

        enableEdgeToEdge()
        setContent {
            InitiateAPhoneCallAppTheme {
                val navController = rememberNavController()

                NavHost(
                    navController = navController,
                    startDestination = "login"
                ) {
                    composable("login") {
                        LoginScreen(
                            onLoginSuccess = { token ->
                                // 登录成功后跳转到主页，并传递 token
                                navController.navigate("main/$token") {
                                    popUpTo("login") { inclusive = true }
                                }
                            }
                        )

                        if (false) {
                            LoginScreen(
                                onLoginSuccess = { token ->
                                    // 登录成功后跳转到主页，并传递 token
                                    navController.navigate("main/$token") {
                                        popUpTo("login") { inclusive = true }
                                    }
                                }
                            )
                        } else {
                            LoginSmsScreen(
                                onLoginSuccess = { token ->
                                    // 登录成功后跳转到主页，并传递 token
                                    navController.navigate("main/$token") {
                                        popUpTo("login") { inclusive = true }
                                    }
                                }
                            )
                        }
                    }
                    composable("main/{token}") { backStackEntry ->
                        val token = backStackEntry.arguments?.getString("token") ?: ""
                        MainScreen(
                            authToken = token,
                            onLogout = {
                                PreferenceManager.clearLoginInfo()
                                navController.navigate("login") {
                                    popUpTo("main") { inclusive = true }
                                }
                            }
                        )
                    }
                }
            }
        }
    }

    private fun hasAllPermissions(): Boolean {
        return requiredPermissions.all { permission ->
            ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
                println("✅ 所有权限已授予")
            } else {
                println("❌ 某些权限被拒绝")
                // 可以在这里提示用户权限被拒绝的影响
            }
        }
    }

    companion object {
        private const val PERMISSION_REQUEST_CODE = 1001
    }
}