package com.stand.standapp.ui.chat

import androidx.activity.compose.BackHandler
import androidx.compose.animation.*
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import com.stand.standapp.ui.chat.components.ChatScaffold
import kotlin.math.roundToInt

@Composable
fun FloatingChatWidget() {
    var isExpanded by remember { mutableStateOf(false) }
    val configuration = LocalConfiguration.current
    val density = LocalDensity.current

    val screenWidthPx = with(density) { configuration.screenWidthDp.dp.toPx() }
    val screenHeightPx = with(density) { configuration.screenHeightDp.dp.toPx() }
    val maxWidth = (configuration.screenWidthDp * 0.45f).dp
    val maxHeight = (configuration.screenHeightDp * 0.75f).dp
    val cardWidthPx = with(density) { maxWidth.toPx() }
    val cardHeightPx = with(density) { maxHeight.toPx() }
    val fabSizePx = with(density) { 56.dp.toPx() }
    val paddingPx = with(density) { 16.dp.toPx() }
    val navBarPx = with(density) { 32.dp.toPx() }

    // 👈 FAB偏移量，全屏幕可拖动
    var fabOffsetX by remember { mutableStateOf(0f) }
    var fabOffsetY by remember { mutableStateOf(0f) }

    // 👈 对话框额外偏移（拖动对话框产生）
    var cardDragX by remember { mutableStateOf(0f) }
    var cardDragY by remember { mutableStateOf(0f) }

    if (isExpanded) {
        BackHandler {
            isExpanded = false
        }
    }

    Box(modifier = Modifier.fillMaxSize()) {
        // FAB - 全屏幕可拖动
        if (!isExpanded) {
            FloatingActionButton(
                onClick = { isExpanded = true },
                modifier = Modifier
                    .align(Alignment.BottomEnd)
                    .padding(16.dp)
                    .padding(bottom = 32.dp)
                    .offset {
                        IntOffset(
                            fabOffsetX.roundToInt()
                                .coerceIn(-(screenWidthPx - fabSizePx - paddingPx * 2).toInt(), 0),
                            fabOffsetY.roundToInt()
                                .coerceIn(-(screenHeightPx - fabSizePx - paddingPx * 2 - navBarPx).toInt(), 0)
                        )
                    }
                    .pointerInput(Unit) {
                        detectDragGestures(
                            onDragStart = { },
                            onDragEnd = { },
                            onDragCancel = { },
                            onDrag = { change, dragAmount ->
                                change.consume()
                                fabOffsetX += dragAmount.x
                                fabOffsetY += dragAmount.y
                            }
                        )
                    },
                containerColor = Color(0xFF10B981)
            ) {
                Text("AI", color = Color.White, style = MaterialTheme.typography.titleMedium)
            }
        }

        // 对话框 - 展开后必须在界面内
        if (isExpanded) {
            var visible by remember { mutableStateOf(false) }
            LaunchedEffect(Unit) {
                visible = true
            }

            // 👈 用 FAB 位置计算对话框位置，但强制钳制在屏幕内
            // FAB右下角为基准：对话框应该出现在 FAB 附近
            val fabRight = screenWidthPx - paddingPx * 2 + fabOffsetX  // FAB右边缘
            val fabBottom = screenHeightPx - paddingPx * 2 - navBarPx + fabOffsetY  // FAB下边缘

            // 对话框优先放在 FAB 左上方，如果放不下就贴边
            val rawX = fabRight - cardWidthPx - paddingPx  // FAB左边
            val rawY = fabBottom - cardHeightPx - paddingPx  // FAB上边

            // 👈 关键：钳制到屏幕内
            val clampedX = rawX.coerceIn(0f, screenWidthPx - cardWidthPx)
            val clampedY = rawY.coerceIn(0f, screenHeightPx - cardHeightPx)

            AnimatedVisibility(
                visible = visible,
                enter = fadeIn(animationSpec = tween(300)) + scaleIn(initialScale = 0.8f, animationSpec = tween(300)),
                exit = fadeOut(animationSpec = tween(200)) + scaleOut(targetScale = 0.8f, animationSpec = tween(200)),
                modifier = Modifier
                    .offset {
                        IntOffset(
                            (clampedX + cardDragX).roundToInt()
                                .coerceIn(0, (screenWidthPx - cardWidthPx).toInt()),
                            (clampedY + cardDragY).roundToInt()
                                .coerceIn(0, (screenHeightPx - cardHeightPx).toInt())
                        )
                    }
                    .width(maxWidth)
                    .height(maxHeight)
                    .shadow(8.dp, RoundedCornerShape(16.dp))
                    .background(MaterialTheme.colorScheme.surface, RoundedCornerShape(16.dp))
                    .clip(RoundedCornerShape(16.dp))
            ) {
                ChatScaffold(
                    onClose = {
                        visible = false
                        isExpanded = false
                        // 👈 关闭时把FAB偏移同步（对话框拖动带动FAB）
                        fabOffsetX += cardDragX
                        fabOffsetY += cardDragY
                        cardDragX = 0f
                        cardDragY = 0f
                    },
                    onDrag = { dx, dy ->
                        cardDragX += dx
                        cardDragY += dy
                    }
                )
            }
        }
    }
}
