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

import android.graphics.Bitmap
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.navigation.NavController
import com.img.rabbit.bean.local.LongImageBean
import com.img.rabbit.pages.toolbar.TitleBar
import com.img.rabbit.utils.ExportFormat
import com.img.rabbit.utils.ImageUtils.getBitmapFromUri
import com.img.rabbit.utils.ImageUtils.saveLongToGallery
import github.leavesczy.matisse.CoilImageEngine
import github.leavesczy.matisse.Matisse
import github.leavesczy.matisse.MatisseContract
import github.leavesczy.matisse.MediaResource
import github.leavesczy.matisse.MediaType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


import androidx.compose.ui.graphics.asAndroidBitmap
import io.moyuru.cropify.Cropify
import io.moyuru.cropify.CropifyOption
import io.moyuru.cropify.rememberCropifyState

@Composable
fun LongImageScreen(navController: NavController) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    var imageItems by remember { mutableStateOf<List<LongImageBean>>(emptyList()) }
    var editingIndex by remember { mutableStateOf<Int?>(null) }

    val coroutineScope = rememberCoroutineScope()
    val mediaPickerLauncher =
        rememberLauncherForActivityResult(contract = MatisseContract()) { result: List<MediaResource>? ->
            if (!result.isNullOrEmpty()) {
                scope.launch(Dispatchers.IO) {
                    val newItems = result.mapNotNull { mediaResource ->
                        val bitmap = getBitmapFromUri(context, mediaResource.uri)
                        bitmap?.let {
                            LongImageBean(uri = mediaResource.uri, bitmap = it)
                        }
                    }

                    withContext(Dispatchers.Main) {
                        imageItems = imageItems + newItems
                    }
                }

            }
        }

    Scaffold {
        LaunchedEffect(Unit) {
            val matisse = Matisse(
                maxSelectable = 10,
                imageEngine = CoilImageEngine(),
                mediaType = MediaType.ImageOnly
            )
            mediaPickerLauncher.launch(matisse)
        }
        Column (
            modifier = Modifier.fillMaxSize().background(Color(0xFFF4F4F4))
        ) {
            TitleBar(
                navController = navController,
                paddingValues = it,
                title = "拼长图",
                showSave = true
            ){
                coroutineScope.launch {
                    saveLongToGallery(context = context, items = imageItems, format = ExportFormat.JPG){ fileName, isSuccess ->
                        if (isSuccess) {
                            Toast.makeText(context, "已保存至 $fileName", Toast.LENGTH_SHORT).show()
                        } else {
                            Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }

            // 2. 预览列表（支持每张图独立缩放）
            LazyColumn(
                modifier = Modifier.weight(1f).padding(start = 30.dp, end = 30.dp, bottom = 30.dp)
            ) {
                itemsIndexed(
                    items = imageItems,
                    // 使用 URI 和 Bitmap 的 hashCode 组合作为 Key
                    key = { index, item -> "${item.uri}_${item.bitmap.hashCode()}" }
                ) { index, item ->
                    Box(modifier = Modifier
                        .fillMaxWidth()
                        .clipToBounds()
                        .clickable { editingIndex = index }
                    ) {
                        Image(
                            bitmap = item.bitmap.asImageBitmap(),
                            contentDescription = null,
                            contentScale = ContentScale.FillWidth,
                            modifier = Modifier.fillMaxWidth().wrapContentHeight()
                        )
                    }
                }
            }
            editingIndex?.let { index ->
                FullScreenCropDialog(
                    item = imageItems[index],
                    onDismiss = { editingIndex = null },
                    onConfirmed = { croppedBitmap ->
                        val newList = imageItems.toMutableList()
                        newList[index] = imageItems[index].copy(bitmap = croppedBitmap)
                        imageItems = newList
                        editingIndex = null
                    }
                )
            }

        }

    }
}


@Composable
fun FullScreenCropDialog(
    item: LongImageBean,
    onDismiss: () -> Unit,
    onConfirmed: (Bitmap) -> Unit
) {
    val cropifyState = rememberCropifyState()
    val cropifyOption = remember {
        CropifyOption(
            frameColor = Color.Cyan,
            gridColor = Color.White.copy(alpha = 0.5f),
        )
    }

    Dialog(
        onDismissRequest = onDismiss,
        properties = DialogProperties(usePlatformDefaultWidth = false)
    ) {
        Surface(modifier = Modifier.fillMaxSize(), color = Color.Black) {
            Box(modifier = Modifier.fillMaxSize()) {
                Cropify(
                    bitmap = item.bitmap.asImageBitmap(),
                    state = cropifyState,
                    option = cropifyOption, // 传入配置项
                    modifier = Modifier.fillMaxSize().padding(bottom = 100.dp),
                    onImageCropped = { croppedImageBitmap ->
                        onConfirmed(croppedImageBitmap.asAndroidBitmap())
                    }
                )

                Row(
                    modifier = Modifier
                        .align(Alignment.BottomCenter)
                        .padding(bottom = 40.dp)
                        .fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceEvenly
                ) {
                    TextButton(onClick = onDismiss) {
                        Text("取消", color = Color.White)
                    }
                    Button(
                        onClick = {
                            // 4. 触发裁剪动作
                            cropifyState.crop()
                        }
                    ) {
                        Text("确定裁剪")
                    }
                }
            }
        }
    }
}




@Preview(showBackground = true)
@Composable
private fun PreviewLongImageScreen(){
    LongImageScreen(navController = NavController(LocalContext.current))
}