package com.img.rabbit.pages.screen.make

import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.util.Log
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.gestures.forEachGesture
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
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.RoundedCornerShape
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.center
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asAndroidBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.graphics.layer.drawLayer
import androidx.compose.ui.graphics.rememberGraphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.unit.toSize
import androidx.navigation.NavController
import com.img.rabbit.R
import com.img.rabbit.components.DrawingBoardCertificatePicker
import com.img.rabbit.config.CommonData.resizes
import com.img.rabbit.pages.toolbar.TitleBar
import com.img.rabbit.utils.ExportFormat
import com.img.rabbit.utils.ImageUtils
import com.img.rabbit.utils.ImageUtils.saveCanvasToGallery
import kotlinx.coroutines.launch

@Composable
fun ResizeScreen(navController: NavController) {
    val context = LocalContext.current
    val dealTarget = "RESIZE"
    // 图片显示区域 - 支持头像编辑(用于最终数据的导出保存Bitmap)
    val graphicsLayer = rememberGraphicsLayer()
    val coroutineScope = rememberCoroutineScope()
    //加载图片参数
    val widthParam = navController.previousBackStackEntry?.savedStateHandle?.get<Float>("width") ?: 23f
    val heightParam = navController.previousBackStackEntry?.savedStateHandle?.get<Float>("height") ?: 35f


    // 当前选中的尺寸
    val selectedSize = remember { mutableStateOf(resizes.first { it.width == widthParam && it.height == heightParam }) }

    // 加载中状态
    val isLoading = remember { mutableStateOf(false) }
    // 人物图片选择相关状态
    val selectedImageUri = remember { mutableStateOf<Uri?>(null) }
    val resizeBitmap = remember { mutableStateOf<Bitmap?>(null) }


    var selectedTarget by remember { mutableStateOf<String?>(null) }
    // 编辑状态
    val transform = remember { mutableStateOf(TransformState()) }

    // 图片选择启动器
    val imagePickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri ->
        uri?.let {
            selectedImageUri.value = it
            isLoading.value = true

            // 执行抠图操作
            Thread {
                try {
                    val originalBitmap = ImageUtils.getBitmapFromUri(context, it)
                    originalBitmap?.let { bitmap ->
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                            context.mainExecutor.execute {
                                resizeBitmap.value = bitmap
                                isLoading.value = false

                                // 重置头像变换
                                transform.value = TransformState()
                            }
                        }

                    }

                } catch (e: Exception) {
                    Log.e("ResizeScreen", "加载图片失败: ${e.message}")
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                        context.mainExecutor.execute {
                            isLoading.value = false
                            Toast.makeText(context, "加载失败，请重试", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }.start()
        }
    }

    // 辅助函数：判断点击位置
    fun hitTest(tap: Offset, state: TransformState, bmp: Bitmap?, canvasCenter: Offset): Boolean {
        if (bmp == null) return false
        val w = bmp.width * state.scale
        val h = bmp.height * state.scale
        val left = canvasCenter.x + state.offset.x - w / 2
        val top = canvasCenter.y + state.offset.y - h / 2
        return tap.x in left..(left + w) && tap.y in top..(top + h)
    }

    Scaffold{
        LaunchedEffect(Unit) {
            imagePickerLauncher.launch("image/*")
        }

        Column(
            modifier = Modifier.fillMaxSize().background(Color(0xFFF4F4F4))
        ) {
            TitleBar(navController = navController, paddingValues = it, title = "", showSave = true){
                // 保存图片
                coroutineScope.launch {
                    // 从 Layer 捕获 Bitmap
                    val bitmap = graphicsLayer.toImageBitmap().asAndroidBitmap()
                    // 保存图片到系统相册(图片已按比例裁剪)
                    saveCanvasToGallery(context, bitmap, ExportFormat.JPG){fileName, isSuccess ->
                        if(isSuccess){
                            Toast.makeText(context, "已保存为: $fileName", Toast.LENGTH_SHORT).show()
                        }else{
                            Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show()
                        }
                    }

                    /*
                    // 保存图片到系统相册(指定尺寸，如果targetWidth与targetHeight比原始值小太多会导致图片模糊)
                    saveCanvasToGallery(context, bitmap, ExportFormat.JPG, selectedSize.value.width.toInt(), selectedSize.value.height.toInt()){fileName, isSuccess ->
                        if(isSuccess){
                            Toast.makeText(context, "已保存为: $fileName", Toast.LENGTH_SHORT).show()
                        }else{
                            Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show()
                        }
                    }
                     */
                }
            }

            Box(
                modifier = Modifier
                    .fillMaxSize()
            ){
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 38.dp, end = 38.dp, top = 14.dp)
                        .aspectRatio(selectedSize.value.width/selectedSize.value.height)
                        .background(Color(0xFFFFFFFF))
                        .border(1.dp, Color(0xFFD8D8D8))
                ){

                    if (isLoading.value) {
                        // 加载中状态
                        Column(
                            modifier = Modifier.align(Alignment.Center)
                        ) {
                            Image(
                                painter = painterResource(id = R.mipmap.ic_loading),
                                contentDescription = "加载效果图片",
                                modifier = Modifier.size(48.dp)
                            )
                            Text(
                                text = "加载中...",
                                color = Color(0xFF767676),
                                fontSize = 12.sp,
                                modifier = Modifier.padding(top = 8.dp)
                            )
                        }
                    } else if (resizeBitmap.value != null) {
                        // 显示合成结果(原始图片)
                        Canvas(
                            modifier = Modifier
                                .fillMaxSize()
                                .drawWithContent {
                                    // 将内容绘制到 graphicsLayer 中
                                    graphicsLayer.record {
                                        this@drawWithContent.drawContent()
                                    }
                                    drawLayer(graphicsLayer)
                                }
                                .clipToBounds()
                                .pointerInput(Unit) {
                                    forEachGesture {
                                        awaitPointerEventScope {
                                            val down = awaitFirstDown()
                                            val center = size.toSize().center

                                            selectedTarget = when {
                                                hitTest(down.position, transform.value, resizeBitmap.value, center) -> dealTarget
                                                else -> null
                                            }
                                        }
                                    }
                                }
                                .pointerInput(Unit) {
                                    detectTransformGestures { _, pan, zoom, rotation ->
                                        selectedTarget?.let { target ->
                                            // 更新逻辑保持不变...
                                            val stateRef = transform

                                            val bmp = resizeBitmap.value

                                            bmp?.let { b ->
                                                val current = stateRef.value
                                                val newScale = (current.scale * zoom).coerceIn(0.1f, 5f)
                                                stateRef.value = current.copy(
                                                    offset = current.offset + pan,
                                                    scale = newScale,
                                                    rotation = if (target == dealTarget) current.rotation + rotation else current.rotation
                                                )
                                            }
                                        }
                                    }
                                }
                        ) {
                            val canvasCenter = center
                            resizeBitmap.value?.let { bmp ->
                                withTransform({
                                    translate(transform.value.offset.x, transform.value.offset.y)
                                    rotate(transform.value.rotation, canvasCenter)
                                    scale(transform.value.scale, transform.value.scale, canvasCenter)
                                }) {
                                    drawImage(bmp.asImageBitmap(), Offset(canvasCenter.x - bmp.width/2, canvasCenter.y - bmp.height/2))
                                }
                            }
                        }

                    } else {
                        // 空状态
                        Column(
                            modifier = Modifier.align(Alignment.Center)
                        ) {
                            Image(
                                painter = painterResource(id = R.mipmap.ic_image_empty_pld),
                                contentDescription = "截图",
                            )
                            Text(
                                text = "去相册选一张美照吧~",
                                color = Color(0xFFD8D8D8),
                                fontSize = 12.sp,
                                modifier = Modifier.align(Alignment.CenterHorizontally)
                            )
                        }
                    }
                }

                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .align(Alignment.BottomCenter)
                ) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 14.dp, vertical = 9.dp)
                            .background(Color(0xFFAAAAAA), shape = RoundedCornerShape(7.dp))
                            .align(Alignment.CenterHorizontally)
                    ){

                        Text(
                            text = "将已有证件照尺寸进行修改，用于适配各种场景",
                            color = Color(0xFFFFFFFF),
                            fontSize = 14.sp,
                            fontWeight = FontWeight.Normal,
                            modifier = Modifier.align(Alignment.Center)
                        )
                    }

                    Box(Modifier.height(14.dp))

                    //底部画板
                    DrawingBoardCertificatePicker(
                        //尺寸列表数据
                        sizes = resizes,
                        //选中
                        selectedSize = selectedSize,
                    )
                }
            }
        }
    }
}