package com.aiosman.ravenow.ui.crop

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
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.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Icon
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewModelScope
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.account.AccountEditViewModel
import com.aiosman.ravenow.ui.agent.AddAgentViewModel
import com.aiosman.ravenow.ui.composables.StatusBarSpacer
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import com.image.cropview.CropType
import com.image.cropview.EdgeType
import com.image.cropview.ImageCrop
import kotlinx.coroutines.launch
import java.io.InputStream
import com.aiosman.ravenow.AppState
@Composable
fun ImageCropScreen() {
    var imageCrop by remember { mutableStateOf<ImageCrop?>(null) }
    val context = LocalContext.current
    val configuration = LocalConfiguration.current
    val screenWidth = configuration.screenWidthDp
    var imageWidthInDp by remember { mutableStateOf(0) }
    var imageHeightInDp by remember { mutableStateOf(0) }
    var density = LocalDensity.current
    var navController = LocalNavController.current
    
    var imagePickLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        uri?.let {
            val bitmap = uriToBitmap(context = context, uri = it)
            if (bitmap != null) {
                val aspectRatio = bitmap.height.toFloat() / bitmap.width.toFloat()
                imageHeightInDp = (imageWidthInDp.toFloat() * aspectRatio).toInt()
                imageCrop = ImageCrop(bitmap)
            }
        }
        if (uri == null) {
            // 用户取消图片选择，清除已裁剪的图片
            AccountEditViewModel.croppedBitmap = null
            navController.popBackStack()
        }
    }
    val systemUiController = rememberSystemUiController()
    LaunchedEffect(Unit) {
        systemUiController.setStatusBarColor(darkIcons = false, color = Color.Black)
        imagePickLauncher.launch("image/*")
    }
    DisposableEffect(Unit) {
        onDispose {
            imageCrop = null
            val isDarkMode = AppState.darkMode
            systemUiController.setStatusBarColor(
                darkIcons = !isDarkMode,
                color = if(isDarkMode)Color.Black else Color.White
            )
        }
    }
    Column(
        modifier = Modifier.background(Color.Black).fillMaxSize()
    ) {
        StatusBarSpacer()
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 8.dp, horizontal = 16.dp)
        ) {
            Image(
                painter = painterResource(R.drawable.rider_pro_back_icon),
                contentDescription = null,
                modifier = Modifier.clickable {
                    // 用户取消头像选择，清除已裁剪的图片
                    AccountEditViewModel.croppedBitmap = null
                    navController.popBackStack()
                },
                colorFilter = ColorFilter.tint(Color.White)
            )
            Spacer(
                modifier = Modifier.weight(1f)
            )
            Icon(
                Icons.Default.Check,
                contentDescription = null,
                tint = Color.White,
                modifier = Modifier.clickable {
                    imageCrop?.let {
                        val bitmap = it.onCrop()
                        
                        // 专门处理个人资料头像
                        // 只设置裁剪后的图片，不立即上传，等待用户在编辑资料界面点击保存
                        AccountEditViewModel.croppedBitmap = bitmap
                        navController.popBackStack()
                    }
                }
            )
        }
        Box(
            modifier = Modifier.fillMaxWidth().padding(24.dp)
        ) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(imageHeightInDp.dp)
                    .onGloballyPositioned {
                        with(density) {
                            imageWidthInDp = it.size.width.toDp().value.toInt()
                        }
                    }
            ) {
                imageCrop?.ImageCropView(
                    modifier = Modifier.fillMaxSize(),
                    guideLineColor = Color.White,
                    guideLineWidth = 2.dp,
                    edgeCircleSize = 5.dp,
                    cropType = CropType.SQUARE,
                    edgeType = EdgeType.CIRCULAR
                )
            }
        }
    }
}


// Configure ImageCropView.


fun uriToBitmap(context: Context, uri: Uri): Bitmap? {
    return try {
        val inputStream: InputStream? = context.contentResolver.openInputStream(uri)
        BitmapFactory.decodeStream(inputStream)
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}