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

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
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.clickable
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.gestures.forEachGesture
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.layout.wrapContentWidth
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.mutableIntStateOf
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.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.unit.toSize
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import coil3.compose.AsyncImage
import com.img.rabbit.R
import com.img.rabbit.bean.local.ClothingBean
import com.img.rabbit.bean.local.HairstyleBean
import com.img.rabbit.components.AppearanceType
import com.img.rabbit.components.DrawingBoardPicker
import com.img.rabbit.config.CommonData.clothingForFemales
import com.img.rabbit.config.CommonData.clothingForMans
import com.img.rabbit.config.CommonData.colors
import com.img.rabbit.config.CommonData.hairstyleForFemales
import com.img.rabbit.config.CommonData.hairstyleForMans
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 java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import com.img.rabbit.utils.PhotoCutter
import kotlinx.coroutines.launch


// 建议的状态数据结构
data class TransformState(
    val offset: Offset = Offset.Zero,
    val scale: Float = 1f,
    val rotation: Float = 0f
)

// 服装和发型资源管理类
object ResourceManager {
    // 加载服装资源
    fun loadClothingResource(context: Context, resId: Int): Bitmap? {
        return try {
            BitmapFactory.decodeResource(context.resources, resId)
        } catch (e: Exception) {
            Log.e("ResourceManager", "加载服装资源失败: ${e.message}")
            null
        }
    }

    // 加载发型资源
    fun loadHairstyleResource(context: Context, resId: Int): Bitmap? {
        return try {
            BitmapFactory.decodeResource(context.resources, resId)
        } catch (e: Exception) {
            Log.e("ResourceManager", "加载发型资源失败: ${e.message}")
            null
        }
    }
}

@Composable
fun CutoutScreen(navController: NavController) {
    val context = LocalContext.current
    // 图片显示区域 - 支持头像编辑(用于最终数据的导出保存Bitmap)
    val graphicsLayer = rememberGraphicsLayer()
    val coroutineScope = rememberCoroutineScope()
    // 抠图加载中状态
    val isLoading = remember { mutableStateOf(false) }

    val widthParam = navController.previousBackStackEntry?.savedStateHandle?.get<Float>("width") ?: 23f
    val heightParam = navController.previousBackStackEntry?.savedStateHandle?.get<Float>("height") ?: 35f

    //显示服装和发型
    val viewClothing = remember { mutableStateOf(ViewType.VISIBLE) }
    val viewHairstyle = remember { mutableStateOf(ViewType.VISIBLE) }

    // 人物图片选择和抠图相关状态
    val selectedImageUri = remember { mutableStateOf<Uri?>(null) }
    val cutoutResultBitmap = remember { mutableStateOf<Bitmap?>(null) }

    // 头像编辑状态
    val headTransform = remember { mutableStateOf(TransformState()) }
    val clothesTransform = remember { mutableStateOf(TransformState()) }
    val hairTransform = remember { mutableStateOf(TransformState()) }

    var selectedTarget by remember { mutableStateOf<String?>(null) }

    // 辅助函数：判断点击位置
    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)
    }

    // 服装和发型资源
    val selectedClothingBitmap = remember { mutableStateOf<Bitmap?>(null) }
    val selectedHairstyleBitmap = remember { mutableStateOf<Bitmap?>(null) }

    // 当前选中的外观
    val selectedAppearance = remember { mutableStateOf(AppearanceType.BACKGROUND) }
    // 当前选中的颜色索引
    val selectedColorIndex = remember { mutableIntStateOf(0) }
    // 当前选中的衣服
    val selectedClothing = remember { mutableStateOf(clothingForFemales.getOrNull(0)) }
    // 当前选中的发型
    val selectedHairstyle = remember { mutableStateOf(hairstyleForFemales.getOrNull(0)) }
    // 当前选中的尺寸
    val selectedSize = remember { mutableStateOf(resizes.first { it.width == widthParam && it.height == heightParam }) }


    // 图片选择启动器
    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 ->
                        PhotoCutter.cutPureHead(bitmap) { croppedBitmap ->
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                                context.mainExecutor.execute {
                                    cutoutResultBitmap.value = croppedBitmap
                                    isLoading.value = false

                                    // 重置头像变换
                                    headTransform.value = TransformState()
                                }
                            }
                        }
                    }
                } catch (e: Exception) {
                    Log.e("CutoutScreen", "抠图失败: ${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 loadClothingResource(clothing: ClothingBean?) {
        if(clothing?.clothing == null){
            selectedClothingBitmap.value = null
        }else{
            Thread {
                val bitmap = ResourceManager.loadClothingResource(context, clothing.clothing)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    context.mainExecutor.execute {
                        selectedClothingBitmap.value = bitmap
                    }
                }
            }.start()
        }
    }

    // 加载发型资源
    fun loadHairstyleResource(hairstyle: HairstyleBean?) {
        if(hairstyle?.hairstyle == null){
            selectedHairstyleBitmap.value = null
        }else{
            Thread {
                val bitmap = ResourceManager.loadHairstyleResource(context, hairstyle.hairstyle)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    context.mainExecutor.execute {
                        selectedHairstyleBitmap.value = bitmap
                    }
                }
            }.start()
        }
    }

    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
                        )
                        .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 (cutoutResultBitmap.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

                                            // 1. 修改判定逻辑：只有当服装可见时，才进行它的 hitTest
                                            selectedTarget = when {
                                                // 处理发型
                                                viewHairstyle.value == ViewType.VISIBLE && hitTest(down.position, hairTransform.value, selectedHairstyleBitmap.value, center) -> "HAIR"

                                                // 处理服装
                                                viewClothing.value == ViewType.VISIBLE && hitTest(down.position, clothesTransform.value, selectedClothingBitmap.value, center) -> "CLOTHES"

                                                hitTest(down.position, headTransform.value, cutoutResultBitmap.value, center) -> "HEAD"
                                                else -> null
                                            }
                                        }
                                    }
                                }
                                .pointerInput(Unit) {
                                    detectTransformGestures { _, pan, zoom, rotation ->
                                        selectedTarget?.let { target ->
                                            // 更新逻辑保持不变...
                                            val stateRef = when(target) {
                                                "HEAD" -> headTransform
                                                "CLOTHES" -> clothesTransform
                                                else -> hairTransform
                                            }
                                            val bmp = when(target) {
                                                "HEAD" -> cutoutResultBitmap.value
                                                "CLOTHES" -> selectedClothingBitmap.value
                                                else -> selectedHairstyleBitmap.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 == "HEAD") current.rotation + rotation else current.rotation
                                                )
                                            }
                                        }
                                    }
                                }
                        ) {
                            val canvasCenter = center

                            // 1. 绘制背景
                            drawRect(colors[selectedColorIndex.intValue])

                            // 2. 绘制头像
                            cutoutResultBitmap.value?.let { bmp ->
                                withTransform({
                                    translate(headTransform.value.offset.x, headTransform.value.offset.y)
                                    rotate(headTransform.value.rotation, canvasCenter)
                                    scale(headTransform.value.scale, headTransform.value.scale, canvasCenter)
                                }) {
                                    drawImage(bmp.asImageBitmap(), Offset(canvasCenter.x - bmp.width/2, canvasCenter.y - bmp.height/2))
                                }
                            }

                            // 3. 绘制服装 (根据状态[viewClothing]显示)
                            if (viewClothing.value == ViewType.VISIBLE) {
                                selectedClothingBitmap.value?.let { bmp ->
                                    withTransform({
                                        translate(clothesTransform.value.offset.x, clothesTransform.value.offset.y)
                                        scale(clothesTransform.value.scale, clothesTransform.value.scale, canvasCenter)
                                    }) {
                                        drawImage(bmp.asImageBitmap(), Offset(canvasCenter.x - bmp.width/2, canvasCenter.y - bmp.height/2))
                                    }
                                }
                            }

                            // 4. 绘制发型 (根据状态[viewHairstyle]显示)
                            if (viewHairstyle.value == ViewType.VISIBLE) {
                                selectedHairstyleBitmap.value?.let { bmp ->
                                    withTransform({
                                        translate(hairTransform.value.offset.x, hairTransform.value.offset.y)
                                        scale(hairTransform.value.scale, hairTransform.value.scale, canvasCenter)
                                    }) {
                                        drawImage(bmp.asImageBitmap(), Offset(canvasCenter.x - bmp.width/2, canvasCenter.y - bmp.height/2))
                                    }
                                }
                            }
                        }


                    } else if (selectedImageUri.value != null) {
                        // 显示选中的原始图片
                        AsyncImage(
                            model = selectedImageUri.value,
                            contentDescription = "选中的图片",
                            modifier = Modifier.fillMaxSize(),
                            contentScale = androidx.compose.ui.layout.ContentScale.Fit
                        )
                    } 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)
                ) {
                    Row(
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        if (selectedAppearance.value == AppearanceType.CLOTHING || selectedAppearance.value == AppearanceType.HAIRSTYLE) {
                            // 服装和发型查看
                            Row(
                                modifier = Modifier.fillMaxWidth().weight(1f).padding(start = 16.dp)
                            ) {
                                ViewOption(
                                    viewType = viewClothing.value,
                                    title = "服装",
                                    onClick = {
                                        viewClothing.value = if (viewClothing.value == ViewType.HIDE) ViewType.VISIBLE else ViewType.HIDE
                                    }
                                )
                                Box(modifier = Modifier.wrapContentSize().padding(end = 8.dp))
                                ViewOption(
                                    viewType = viewHairstyle.value,
                                    title = "发型",
                                    onClick = {
                                        viewHairstyle.value = if (viewHairstyle.value == ViewType.HIDE) ViewType.VISIBLE else ViewType.HIDE
                                    }
                                )
                            }
                        } else {
                            Row(
                                modifier = Modifier.fillMaxWidth().weight(1f).padding(start = 16.dp)
                            ) {}
                        }

                        /*
                        // 说明
                        Row(
                            modifier = Modifier.wrapContentSize().padding(end = 16.dp).align(Alignment.Bottom)
                        ) {
                            Image(
                                painter = painterResource(id = R.mipmap.ic_info),
                                contentDescription = "说明",
                                modifier = Modifier
                                    .size(14.dp)
                                    .align(Alignment.CenterVertically)
                                    .clip(CircleShape)
                                    .background(Color(0xFFF4F4F4))
                            )
                            Text(
                                text = "使用说明",
                                color = Color(0xFF767676),
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Normal,
                                modifier = Modifier.align(Alignment.Bottom).padding(start = 4.dp)
                            )
                        }
                         */
                    }

                    // 底部画板
                    DrawingBoardPicker(
                        // 颜色
                        colors = colors,
                        // 服装
                        clothingForMans = clothingForMans,
                        clothingForFemales = clothingForFemales,
                        // 发型
                        hairstyleForMans = hairstyleForMans,
                        hairstyleForFemales = hairstyleForFemales,
                        // 尺寸
                        sizes = resizes,
                        // 选中
                        selectedAppearance = selectedAppearance,
                        selectedColorIndex = selectedColorIndex,
                        selectedClothing = selectedClothing,
                        selectedHairstyle = selectedHairstyle,
                        selectedSize = selectedSize,
                        // 新增回调函数
                        onClothingSelected = { clothing ->
                            loadClothingResource(clothing)
                        },
                        onHairstyleSelected = { hairstyle ->
                            loadHairstyleResource(hairstyle)
                        }
                    )
                }
            }
        }
    }
}

// 保存合成结果
private fun saveCompositeResult(context: Context, compositeBitmap: Bitmap): Uri? {
    try {
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val imageFileName = "COMPOSITE_${timeStamp}.png"

        val storageDir = context.getExternalFilesDir(android.os.Environment.DIRECTORY_PICTURES)
        val imageFile = File(storageDir, imageFileName)

        val outputStream = FileOutputStream(imageFile)
        compositeBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
        outputStream.flush()
        outputStream.close()

        // 更新媒体库
        val mediaScanIntent = android.content.Intent(android.content.Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        val uri = Uri.fromFile(imageFile)
        mediaScanIntent.data = uri
        context.sendBroadcast(mediaScanIntent)

        return uri
    } catch (e: Exception) {
        Log.e("CutoutScreen", "保存合成结果失败: ${e.message}")
        return null
    }
}

@Composable
private fun ViewOption(
    viewType: ViewType,
    title: String,
    onClick: () -> Unit,
){
    Box(
        modifier = Modifier
            .wrapContentWidth()
            .wrapContentHeight()
            .background(
                Color(0xFFFFFFFF),
                shape = RoundedCornerShape(359.dp),
            )
            .border(
                width = 1.dp,
                color = if(viewType == ViewType.VISIBLE) Color(0xFF000000) else Color(0xFFEDEDED),
                shape = RoundedCornerShape(359.dp)
            )
            .clickable(
                indication = null,
                interactionSource = remember { MutableInteractionSource() }
            ) {
                onClick()
            }
    ) {
        Row(
            modifier = Modifier
                .align(Alignment.Center)
                .padding(start = 5.dp, end = 7.dp)
        ) {
            Image(
                painter = painterResource(id = if(viewType == ViewType.VISIBLE) R.mipmap.ic_view else R.mipmap.ic_hide),
                contentDescription = "图标",
                modifier = Modifier
                    .wrapContentWidth()
                    .wrapContentHeight()
                    .align(Alignment.CenterVertically)
            )
            Text(
                title,
                color = if(viewType == ViewType.VISIBLE) Color(0xFF1A1A1A) else Color(0xFF767676),
                fontSize = 14.sp,
                lineHeight = 14.sp,
                fontWeight = FontWeight.Normal,
                modifier = Modifier
                    .wrapContentWidth()
                    .wrapContentHeight()
                    .padding(vertical = 2.dp)
            )
        }
    }
}


enum class ViewType {
    HIDE,
    VISIBLE
}

@Preview(showBackground = true)
@Composable
private fun PreviewCutoutScreen() {
    CutoutScreen(navController = rememberNavController())
}
