package com.example.kmptpc_compose_sample.demos.foundation

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.draganddrop.dragAndDropSource
import androidx.compose.foundation.draganddrop.dragAndDropTarget
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.draganddrop.DragAndDropEvent
import androidx.compose.ui.draganddrop.DragAndDropTarget
import androidx.compose.ui.draganddrop.DragAndDropTransferData
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.unit.dp

// 平台特定的创建函数，需要在各平台实现
expect fun createDragAndDropTransferData(item: String): DragAndDropTransferData?

@Composable
internal fun FoundationDragAndDropDemo() {
    var droppedItems by remember { mutableStateOf<List<String>>(emptyList()) }
    var dragStatus by remember { mutableStateOf<String>("等待拖放操作...") }
    
    val draggableItems = remember {
        listOf("项目 1", "项目 2", "项目 3", "项目 4", "项目 5")
    }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        Text(
            text = "拖放测试",
            style = MaterialTheme.typography.h5
        )
        
        Text(
            text = "说明：长按下方卡片进行拖拽，然后拖放到右侧的目标区域",
            style = MaterialTheme.typography.body2,
            color = MaterialTheme.colors.onSurface.copy(alpha = 0.7f)
        )
        
        // 状态显示
        Card(
            backgroundColor = Color.LightGray.copy(alpha = 0.3f),
            modifier = Modifier.fillMaxWidth()
        ) {
            Column(
                modifier = Modifier.padding(12.dp)
            ) {
                Text(
                    text = "状态：$dragStatus",
                    style = MaterialTheme.typography.body2
                )
                if (droppedItems.isNotEmpty()) {
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = "已接收的项目：${droppedItems.joinToString(", ")}",
                        style = MaterialTheme.typography.body2
                    )
                }
            }
        }
        
        // 主内容区域：左侧可拖拽项目，右侧接收区域
        Row(
            modifier = Modifier.fillMaxSize(),
            horizontalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // 左侧：可拖拽的项目列表
            Column(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxHeight(),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Text(
                    text = "可拖拽项目",
                    style = MaterialTheme.typography.subtitle1
                )
                
                draggableItems.forEach { item ->
                    DraggableCard(
                        item = item,
                        onDragStart = {
                            dragStatus = "正在拖拽: $item"
                        },
                        onDragEnd = {
                            dragStatus = "拖拽结束: $item"
                        }
                    )
                }
            }
            
            // 右侧：拖放目标区域
            DropTargetArea(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxHeight(),
                onDrop = { item ->
                    if (!droppedItems.contains(item)) {
                        droppedItems = droppedItems + item
                        dragStatus = "成功接收: $item"
                    } else {
                        dragStatus = "项目已存在: $item"
                    }
                },
                onEnter = {
                    dragStatus = "进入目标区域"
                },
                onExit = {
                    dragStatus = "离开目标区域"
                }
            )
        }
    }
}

@Composable
private fun DraggableCard(
    item: String,
    onDragStart: () -> Unit,
    onDragEnd: () -> Unit
) {
    var isDragging by remember { mutableStateOf(false) }
    
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .dragAndDropSource(
                transferData = { offset ->
                    println("Drag----------dragAndDropSource transferData called, offset=$offset")
                    onDragStart()
                    isDragging = true
                    // 创建传输数据，使用平台特定的实现
                    createDragAndDropTransferData(item)
                }
            )
            .then(
                if (isDragging) {
                    Modifier.alpha(0.5f)
                } else {
                    Modifier
                }
            ),
        backgroundColor = if (isDragging) {
            MaterialTheme.colors.primary.copy(alpha = 0.3f)
        } else {
            MaterialTheme.colors.surface
        },
        elevation = if (isDragging) 8.dp else 2.dp
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = item,
                style = MaterialTheme.typography.body1
            )
            Text(
                text = "长按拖拽",
                style = MaterialTheme.typography.caption,
                color = MaterialTheme.colors.primary
            )
        }
    }
    
    // 重置拖拽状态（在实际实现中，这应该通过事件回调处理）
    LaunchedEffect(item) {
        kotlinx.coroutines.delay(100)
        isDragging = false
        onDragEnd()
    }
}

@Composable
private fun DropTargetArea(
    modifier: Modifier = Modifier,
    onDrop: (String) -> Unit,
    onEnter: () -> Unit,
    onExit: () -> Unit
) {
    var isDragOver by remember { mutableStateOf(false) }
    
    val dropTarget = object : DragAndDropTarget {
        override fun onStarted(event: DragAndDropEvent) {
            // 检查是否可以接收
            println("Drag----------DropTargetArea.onStarted: called")
        }
        
        override fun onEntered(event: DragAndDropEvent) {
            println("Drag----------DropTargetArea.onEntered: called")
            isDragOver = true
            onEnter()
        }
        
        override fun onMoved(event: DragAndDropEvent) {
            // 拖拽移动中
            println("Drag----------DropTargetArea.onMoved: called")
        }
        
        override fun onExited(event: DragAndDropEvent) {
            println("Drag----------DropTargetArea.onExited: called")
            isDragOver = false
            onExit()
        }
        
        override fun onChanged(event: DragAndDropEvent) {
            // 拖拽变化
            println("Drag----------DropTargetArea.onChanged: called")
        }
        
        override fun onDrop(event: DragAndDropEvent): Boolean {
            println("Drag------DropTargetArea.onDrop: called")
            isDragOver = false
            // 尝试获取拖放数据
            // 注意：这里需要根据实际的 DragAndDropTransferData 实现来获取数据
            // 由于当前实现可能还不完整，这里使用占位逻辑
            try {
                // 尝试从事件中提取数据
                // 实际实现需要根据平台特定的 API 来获取数据
                val item = extractItemFromEvent(event)
                println("Drag------DropTargetArea.onDrop: item=$item")
                if (item != null) {
                    onDrop(item)
                    return true
                }
                return false
            } catch (e: Exception) {
                println("Drag------DropTargetArea.onDrop: exception=${e.message}")
                e.printStackTrace()
                return false
            }
        }
        
        override fun onEnded(event: DragAndDropEvent) {
            isDragOver = false
            println("Drag----------DropTargetArea.onEnded: called")
        }
    }
    
    // 用 Box 扩大命中区：dragAndDropTarget 在 Box 上（命中区=整块），Card 内缩+边框，避免刚碰到边框就 LEAVE_TARGET
    Box(
        modifier = modifier
            .dragAndDropTarget(
                shouldStartDragAndDrop = { event ->
                    true
                },
                target = dropTarget
            )
    ) {
        // 边框和背景固定，不在拖入时重绘，避免布局变化导致 LEAVE_TARGET
        Card(
            modifier = Modifier
                .fillMaxSize()
                .padding(4.dp)
                .border(
                    width = 1.dp,
                    color = MaterialTheme.colors.onSurface.copy(alpha = 0.2f),
                    shape = RoundedCornerShape(8.dp)
                ),
            shape = RoundedCornerShape(8.dp),
            backgroundColor = Color.LightGray.copy(alpha = 0.5f)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Text(
                    text = "拖放目标区域",
                    style = MaterialTheme.typography.h6,
                    color = MaterialTheme.colors.onSurface.copy(alpha = 0.6f)
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = "将项目拖放到这里",
                    style = MaterialTheme.typography.body2,
                    color = MaterialTheme.colors.onSurface.copy(alpha = 0.5f)
                )
            }
        }
    }
}

// 平台特定的数据提取函数，需要在各平台实现
expect fun extractItemFromEvent(event: DragAndDropEvent): String?

