package com.aiosman.ravenow.ui.agent

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.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.ContentScale
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.compose.ui.unit.sp
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.lifecycle.viewModelScope
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
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

/**
 * 专门用于智能体头像裁剪的页面
 * 支持创建和编辑两种模式
 */
@Composable
fun AgentImageCropScreen() {
    var imageCrop by remember { mutableStateOf<ImageCrop?>(null) }
    var croppedBitmap by remember { mutableStateOf<Bitmap?>(null) }
    val context = LocalContext.current
    val configuration = LocalConfiguration.current
    var imageWidthInDp by remember { mutableStateOf(0) }
    var imageHeightInDp by remember { mutableStateOf(0) }
    val density = LocalDensity.current
    val navController = LocalNavController.current
    
    // 检查是否在编辑模式（通过检查是否有编辑ViewModel的实例）
    val isEditMode = remember { 
        // 通过检查导航栈或使用其他方式判断
        // 暂时使用一个简单的方法：检查AddAgentViewModel是否正在选择头像
        // 如果不是，则可能是编辑模式
        !AddAgentViewModel.isSelectingAvatar
    }
    
    val 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) {
            // 用户取消选择图片，重置标志
            if (!isEditMode) {
                AddAgentViewModel.isSelectingAvatar = false
            }
            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 {
                    // 用户取消头像选择，重置标志
                    if (!isEditMode) {
                        AddAgentViewModel.isSelectingAvatar = false
                    }
                    navController.popBackStack()
                },
                colorFilter = ColorFilter.tint(Color.White)
            )
            Spacer(modifier = Modifier.weight(1f))
            
            // 确认按钮
            Icon(
                Icons.Default.Check,
                contentDescription = null,
                tint = if (croppedBitmap != null) Color.Green else Color.White,
                modifier = Modifier.clickable {
                    if (croppedBitmap != null) {
                        // 如果已经有裁剪结果，直接返回
                        if (isEditMode) {
                            // 编辑模式：需要找到当前的编辑ViewModel实例
                            // 由于无法直接访问，我们使用一个全局状态或者通过其他方式传递
                            // 暂时先保存到AddAgentViewModel，编辑页面会检查
                            AddAgentViewModel.croppedBitmap = croppedBitmap
                        } else {
                            AddAgentViewModel.croppedBitmap = croppedBitmap
                            // 重置头像选择标志
                            AddAgentViewModel.isSelectingAvatar = false
                            AddAgentViewModel.viewModelScope.launch {
                                AddAgentViewModel.updateAgentAvatar(context)
                                navController.popBackStack()
                            }
                        }
                        navController.popBackStack()
                    } else {
                        // 进行裁剪
                        imageCrop?.let {
                            val bitmap = it.onCrop()
                            croppedBitmap = bitmap
                        }
                    }
                }
            )
        }
        
        // 裁剪预览区域
        Box(
            modifier = Modifier.fillMaxWidth().padding(24.dp)
        ) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(imageHeightInDp.dp)
                    .onGloballyPositioned { coordinates ->
                        with(density) {
                            imageWidthInDp = coordinates.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
                )
            }
        }
        
        // 裁剪结果预览
        croppedBitmap?.let { bitmap ->
            Spacer(modifier = Modifier.height(24.dp))
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(
                        Color.Black.copy(alpha = 0.8f),
                        shape = RoundedCornerShape(12.dp)
                    )
                    .padding(16.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = "✅ 裁剪完成",
                    color = Color.Green,
                    fontSize = 16.sp
                )
                Spacer(modifier = Modifier.height(12.dp))
                CustomAsyncImage(
                    context,
                    bitmap,
                    modifier = Modifier
                        .size(100.dp)
                        .clip(CircleShape)
                        .background(Color.Gray.copy(alpha = 0.3f), CircleShape),
                    contentDescription = "智能体头像预览",
                    contentScale = ContentScale.Crop
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = "点击 ✓ 确认使用此头像",
                    color = Color.White.copy(alpha = 0.8f),
                    fontSize = 12.sp
                )
            }
        }
    }
}

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
    }
}
