package com.img.rabbit.utils

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat

/**
 * 权限管理工具类
 */
object PermissionUtils {

    // 相机权限
    const val CAMERA_PERMISSION = Manifest.permission.CAMERA

    // 存储权限（根据Android版本区分）
    val STORAGE_PERMISSIONS = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        arrayOf(Manifest.permission.READ_MEDIA_IMAGES)
    } else {
        arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
    }

    /**
     * 检查权限是否已授予
     */
    fun hasPermissions(context: Context, vararg permissions: String): Boolean {
        return permissions.all { permission ->
            ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
        }
    }

    /**
     * 检查相机权限
     */
    fun hasCameraPermission(context: Context): Boolean {
        return hasPermissions(context, CAMERA_PERMISSION)
    }

    /**
     * 检查存储权限
     */
    fun hasStoragePermission(context: Context): Boolean {
        return hasPermissions(context, *STORAGE_PERMISSIONS)
    }

    /**
     * 检查所有图片相关权限
     */
    fun hasImagePermissions(context: Context): Boolean {
        return hasCameraPermission(context) && hasStoragePermission(context)
    }

    /**
     * 检查相册权限（只需要存储权限）
     */
    fun hasGalleryPermission(context: Context): Boolean {
        return hasStoragePermission(context)
    }

    /**
     * 跳转到应用设置页面
     */
    fun openAppSettings(context: Context) {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
            data = Uri.fromParts("package", context.packageName, null)
        }
        if (context is Activity) {
            context.startActivity(intent)
        } else {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
        }
    }
}

/**
 * 权限状态数据类
 */
data class PermissionState(
    val hasCameraPermission: Boolean = false,
    val hasStoragePermission: Boolean = false,
    val shouldShowRationale: Boolean = false
)

/**
 * 可组合函数：管理权限请求
 */
@Composable
fun rememberPermissionState(): MutableState<PermissionState> {
    val context = LocalContext.current
    return remember {
        mutableStateOf(
            PermissionState(
                hasCameraPermission = PermissionUtils.hasCameraPermission(context),
                hasStoragePermission = PermissionUtils.hasStoragePermission(context)
            )
        )
    }
}

/**
 * 可组合函数：创建权限请求启动器
 */
@Composable
fun rememberPermissionLauncher(
    context: Context = LocalContext.current,
    onGranted: () -> Unit = {},
    onDenied: () -> Unit = {},
    onRationale: () -> Unit = {}
) = rememberLauncherForActivityResult(
    ActivityResultContracts.RequestMultiplePermissions()
) { permissions ->
    val allGranted = permissions.values.all { it }
    val shouldShowRationale = permissions.keys.any { permission ->
        androidx.core.app.ActivityCompat.shouldShowRequestPermissionRationale(
            context as Activity,
            permission
        )
    }

    if (allGranted) {
        onGranted()
    } else if (shouldShowRationale) {
        onRationale()
    } else {
        onDenied()
    }
}

/**
 * 可组合函数：创建相机权限启动器
 */
@Composable
fun rememberCameraPermissionLauncher(
    context: Context = LocalContext.current,
    onGranted: () -> Unit = {},
    onDenied: () -> Unit = {},
    onRationale: () -> Unit = {}
) = rememberLauncherForActivityResult(
    ActivityResultContracts.RequestPermission()
) { isGranted ->
    if (isGranted) {
        onGranted()
    } else {
        val shouldShowRationale = androidx.core.app.ActivityCompat.shouldShowRequestPermissionRationale(
            context as Activity,
            Manifest.permission.CAMERA
        )
        if (shouldShowRationale) {
            onRationale()
        } else {
            onDenied()
        }
    }
}