package com.img.rabbit.components

import android.annotation.SuppressLint
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
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.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.core.content.FileProvider
import java.io.File

// 首先添加ImageUtils的导入
import androidx.compose.foundation.Image
import androidx.compose.ui.res.painterResource
import coil3.compose.AsyncImage
import com.img.rabbit.R
import kotlin.collections.minus
import kotlin.let

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ImagePicker(
    modifier: Modifier = Modifier,
    imageHeight: Dp = 146.dp,
    aspectRatio: Float = 747f / 395f,
    maxCount: Int = 10,
    addButtonName: String = "添加图片",
    currentImageUris: List<Uri> = emptyList(),
    currentImagePaths: List<String> = emptyList(), // 新增参数
    onImagesUpdated: (currentUri: Uri, uris: List<Uri>) -> Unit,
    onDeleteUpdated: (currentUri: Uri, uris: List<Uri>) -> Unit
) {
    val context = LocalContext.current
    // 添加临时文件管理
    val tempImageUri = remember { mutableStateOf<Uri?>(null) }

    // 新增选择对话框
    var showChoiceDialog by remember { mutableStateOf(false) }

    // 新增大图预览状态
    var previewImageUri by remember { mutableStateOf<Uri?>(null) }

    // 图片路径转Uri的辅助函数
    fun getDisplayImages(): List<Uri> {
        return currentImageUris.ifEmpty {
            currentImagePaths.mapNotNull { path ->
                try {
                    Uri.fromFile(File(path))
                } catch (e: Exception) {
                    null
                }
            }
        }
    }

    // 相册选择逻辑
    val galleryLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.PickVisualMedia()
    ) { uri ->
        uri?.let { uri ->
            if (currentImageUris.size < maxCount) {
                // 更新图片列表和路径列表
                onImagesUpdated( uri, currentImageUris + uri )
            }
        }
    }

    // 拍照逻辑
    val cameraLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.TakePicture()
    ) { success ->
        if (success) {
            tempImageUri.value?.let { uri ->
                if (currentImageUris.size < maxCount) {
                    // 更新图片列表和路径列表
                    onImagesUpdated( uri, currentImageUris + uri )
                }
            }
        }
    }


    if (showChoiceDialog) {
        AlertDialog(
            onDismissRequest = { showChoiceDialog = false },
            title = { Text(text = "选择图片来源", fontSize = 14.sp) },
            text = { Text(text = "请选择拍照或从相册选取, 若无权限点击相册或者拍照后会弹出权限请求", fontSize = 12.sp) },
            confirmButton = {
                TextButton(
                    onClick = {
                        showChoiceDialog = false
                        val uri = FileProvider.getUriForFile(context,"${context.packageName}.fileProvider",File.createTempFile("IMG_", ".jpg", context.externalCacheDir))
                        tempImageUri.value = uri
                        cameraLauncher.launch(uri)
                    }
                ) { Text(text = "拍照", fontSize = 14.sp) }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        showChoiceDialog = false
                        galleryLauncher.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
                    }
                ) { Text(text = "相册", fontSize = 14.sp) }
            }
        )
    }

    // 全屏大图对话框
    previewImageUri?.let { uri ->
        FullScreenDialog(
            onDismiss = { previewImageUri = null }
        ) {
            ZoomableImage(
                uri = uri,
                modifier = Modifier
                    .fillMaxSize()
            )
        }
    }

    LazyRow(modifier = modifier.defaultMinSize(minHeight = (imageHeight + 8.dp))) {
        items(getDisplayImages()) { uri ->
            Box(
                Modifier.padding(4.dp).background(color = Color(0x80E5E5E7), shape = RoundedCornerShape(8.dp))
            ) {
                AsyncImage(
                    model = uri,
                    contentDescription = null,
                    modifier = Modifier
                        .height(imageHeight)
                        .aspectRatio(aspectRatio)
                        .clip(RoundedCornerShape(8.dp))
                        .clickable {
                            previewImageUri = uri
                        }
                )
                val size = if(imageHeight < 150.dp){
                    24.dp
                }else{
                    32.dp
                }
                Image(
                    painter = painterResource(id = R.drawable.ic_close),
                    contentDescription = null,
                    modifier = Modifier
                        .size(size)
                        .aspectRatio(1f) // 设置宽高比为1:1
                        .align(Alignment.TopEnd)
                        .padding(top = 4.dp, end = 4.dp)
                        .clickable{
                            onDeleteUpdated(uri, currentImageUris - uri)
                        }
                )
            }
        }

        item {
            if (currentImageUris.size < maxCount && currentImagePaths.size < maxCount) {
                // 在触发按钮中添加
                if(maxCount==1){
                    AddSingleButton(
                        imageHeight = imageHeight,
                        aspectRatio = aspectRatio,
                        onClick = { showChoiceDialog = true },
                        label = addButtonName,
                    )
                }else{
                    Box(
                        Modifier.defaultMinSize(minHeight = (imageHeight + 8.dp)),
                        contentAlignment = Alignment.BottomCenter
                    ) {
                        AddButton(
                            onClick = { showChoiceDialog = true },
                            label = addButtonName,
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun AddButton(onClick: () -> Unit, label: String = "添加图片") {
    TextButton(
        onClick = onClick,
        modifier = Modifier
            .size(100.dp)
            .padding(4.dp)
            .border(1.dp, Color(0xFFA5A5A5), RoundedCornerShape(8.dp))
    ) {
        Column(horizontalAlignment = Alignment.CenterHorizontally) {
            Icon(Icons.Default.Add, contentDescription = label)
            Text(text = label)
        }
    }
}

@Composable
private fun AddSingleButton(
    imageHeight: Dp = 146.dp,
    aspectRatio: Float = 747f / 395f,
    onClick: () -> Unit,
    label: String = "添加图片"
) {
    TextButton(
        onClick = onClick,
        modifier = Modifier
            .height(imageHeight + 8.dp)
            .aspectRatio(aspectRatio)
            .border(1.dp, Color(0xFFA5A5A5), RoundedCornerShape(8.dp))
    ) {
        if(label ==  "上传头像"){
            Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
                Text(text = label)
            }
        }else{
            Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
                Icon(Icons.Default.Add, contentDescription = label)
                Text(text = label)
            }
        }
    }
}


@Composable
private fun FullScreenDialog(
    onDismiss: () -> Unit,
    content: @Composable () -> Unit
) {
    Dialog(
        onDismissRequest = onDismiss,
        properties = DialogProperties(
            usePlatformDefaultWidth = false,
            decorFitsSystemWindows = false
        )
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Black.copy(alpha = 0.95f))
                .clickable(onClick = onDismiss)
        ) {
            content()
        }
    }
}

@SuppressLint("UnusedBoxWithConstraintsScope", "AutoboxingStateValueProperty")
@Composable
private fun ZoomableImage(uri: Uri, modifier: Modifier = Modifier) {
    val scale = remember { mutableFloatStateOf(1f) }
    val offset = remember { mutableStateOf(Offset.Zero) }

    BoxWithConstraints(modifier = modifier.pointerInput(Unit) {
        detectTransformGestures { _, pan, zoom, _ ->
            scale.floatValue *= zoom
            offset.value += pan
        }
    }) {
        AsyncImage(
            model = uri,
            contentDescription = null,
            modifier = Modifier
                .graphicsLayer {
                    scaleX = scale.value
                    scaleY = scale.value
                    translationX = offset.value.x
                    translationY = offset.value.y
                }
                .align(Alignment.Center)
        )
    }
}