package com.aiosman.ravenow.ui.post

import android.Manifest
import android.content.pm.PackageManager
import android.net.Uri
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material3.BasicAlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon

import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
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.draw.drawBehind
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.draw.scale
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.FileProvider
import androidx.lifecycle.viewModelScope
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.DraggableGrid
import com.aiosman.ravenow.ui.composables.RelPostCard
import com.aiosman.ravenow.ui.composables.StatusBarMaskLayout
import com.aiosman.ravenow.ui.composables.rememberDebouncer
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import kotlinx.coroutines.launch
import java.io.File
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.rememberLottieComposition

/**
 * 发布动态
 */
@Preview
@Composable
fun NewPostScreen() {
    val AppColors = LocalAppTheme.current
    var isAiEnabled by remember { mutableStateOf(false) }
    var isRotating by remember { mutableStateOf(false) }
    var isRequesting by remember { mutableStateOf(false) }
    var buttonBottomY by remember { mutableStateOf(0f) }
    val keyboardController = LocalSoftwareKeyboardController.current
    val density = LocalDensity.current
    val context = LocalContext.current

    val model = NewPostViewModel
    val systemUiController = rememberSystemUiController()
    LaunchedEffect(Unit) {
        systemUiController.setNavigationBarColor(color = Color.Transparent)
        model.init()
    }

    // 退出时自动保存草稿
    DisposableEffect(Unit) {
        onDispose {
            model.saveDraft(context)
        }
    }


    StatusBarMaskLayout(
        darkIcons = !AppState.darkMode,
        modifier = Modifier
            .fillMaxSize()
            .background(
                AppColors.background
            )
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(AppColors.background)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
            ) {
                NewPostTopBar {
                }
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp)
                ) {
                    model.relMoment?.let {
                        Text("Share with")
                        Spacer(modifier = Modifier.height(8.dp))
                        Box(
                            modifier = Modifier
                                .clip(RoundedCornerShape(8.dp))
                                .background(color = AppColors.basicMain)
                                .padding(24.dp)
                        ) {
                            RelPostCard(
                                momentEntity = it,
                                modifier = Modifier.fillMaxWidth()
                            )
                        }
                    }
                }

                AddImageGrid()
                NewPostTextField(stringResource(R.string.moment_content_hint), NewPostViewModel.textContent) { newValue ->
                    NewPostViewModel.textContent = newValue
                }
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(1.dp)
                        .padding(horizontal = 16.dp)
                        .background(AppColors.divider)
                )
                Spacer(modifier = Modifier.height(24.dp))
                val isButtonEnabled = model.textContent.isNotEmpty()
                Row(
                    modifier = Modifier
                        .padding(start = 16.dp)
                        .height(40.dp)
                        .widthIn(min = 100.dp, max = 200.dp)
                        .wrapContentWidth()
                        .clip(RoundedCornerShape(20.dp))
                        .onGloballyPositioned { coordinates ->
                            buttonBottomY = with(density) { coordinates.size.height.toDp().toPx() + coordinates.positionInRoot().y }
                        }
                        .then(
                            if (isButtonEnabled) {
                                Modifier.background(
                                    brush = Brush.linearGradient(
                                        colors = listOf(
                                            Color(0xFF8CDDFF),
                                            Color(0xFF9887FF),
                                            Color(0xFFFF8D28)
                                        ),
                                    )
                                )
                            } else {
                                Modifier.background(Color(0xFFD4D1D6))
                            }
                        )
                        .then(
                            if (isButtonEnabled) {
                                Modifier.noRippleClickable {
                                    model.viewModelScope.launch {
                                        isRequesting = true
                                        try {
                                            model.agentMoment(model.textContent)
                                        } catch (e: Exception) {
                                            e.printStackTrace()
                                            Toast.makeText(
                                                context,
                                                "${e.message ?: "请稍后重试"}",
                                                Toast.LENGTH_SHORT
                                            ).show()
                                        } finally {
                                            isRequesting = false
                                        }
                                    }
                                }
                            } else {
                                Modifier
                            }
                        )
                        .padding(horizontal = 14.dp, vertical = 8.dp),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.Center
                ) {
                    Image(
                        painter = painterResource(id = R.mipmap.icon_ai),
                        contentDescription = null,
                        modifier = Modifier
                            .size(16.dp)
                    )
                    Text(
                        text = stringResource(R.string.moment_ai_co),
                        fontWeight = FontWeight.Normal,
                        fontSize = 13.sp,
                        modifier = Modifier
                            .padding(start = 2.dp),
                        color = Color.White,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                }

                Column(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    BasicTextField(
                        value = model.aiTextContent,
                        onValueChange = { newValue ->
                            model.aiTextContent = newValue
                        },
                        modifier = Modifier
                            .height(160.dp)
                            .heightIn(160.dp)
                            .padding(horizontal = 16.dp, vertical = 10.dp)
                            .fillMaxWidth(),
                        cursorBrush = SolidColor(AppColors.text),
                        textStyle = TextStyle(
                            lineHeight = 24.sp,
                            color = AppColors.text,
                        ),
                        readOnly = true
                    )
                    if (model.aiTextContent.isNotEmpty()) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(horizontal = 16.dp, vertical = 8.dp),
                            horizontalArrangement = Arrangement.End // 靠右对齐
                        ) {
                            // 删除按钮
                            Row(
                                modifier = Modifier
                                    .noRippleClickable {
                                        model.aiTextContent = ""
                                    }
                                    .background(
                                        color = AppColors.basicMain,
                                        shape = RoundedCornerShape(16.dp)
                                    )
                                    .padding(horizontal = 8.dp, vertical = 8.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    painter = painterResource(id = R.drawable.rider_pro_moment_delete),
                                    contentDescription = "delete",
                                    modifier = Modifier.size(16.dp),
                                    tint = AppColors.text
                                )
                                Text(
                                    text = stringResource(R.string.moment_ai_delete),
                                    fontSize = 12.sp,
                                    color = AppColors.text,
                                    modifier = Modifier.padding(start = 4.dp)
                                )
                            }

                            Spacer(modifier = Modifier.width(14.dp))
                            //应用生成文案
                            Row(
                                modifier = Modifier
                                    .noRippleClickable {
                                        if (model.aiTextContent.isNotEmpty()) {
                                            model.textContent = model.aiTextContent
                                        }
                                    }
                                    .background(
                                        color = AppColors.basicMain,
                                        shape = RoundedCornerShape(16.dp)
                                    )
                                    .padding(horizontal = 8.dp, vertical = 8.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    painter = painterResource(id = R.drawable.rider_pro_moment_apply),
                                    contentDescription = "apply",
                                    modifier = Modifier.size(16.dp),
                                    tint = AppColors.text
                                )
                                Text(
                                    text = stringResource(R.string.moment_ai_apply),
                                    fontSize = 12.sp,
                                    color = AppColors.text,
                                    modifier = Modifier.padding(start = 4.dp)
                                )
                            }
                        }
                    }
                }
            }

            // 底部背景图
            if (isRequesting) {
                if (!AppState.darkMode) {
                    Image(
                        painter = painterResource(id = R.mipmap.component),
                        contentDescription = null,
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(400.dp)
                            .align(Alignment.BottomStart)
                            .offset(y = (-40).dp),
                        contentScale = ContentScale.FillBounds
                    )
                }
                
                // 加载动画显示在背景图上方，按钮下方80dp区域
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .offset {
                            val yOffset = (buttonBottomY + with(density) { 60.dp.toPx() }).toInt()
                            IntOffset(x = 0, y = yOffset)
                        },
                    contentAlignment = Alignment.Center
                ) {
                    LottieAnimation(
                        composition = rememberLottieComposition(LottieCompositionSpec.Asset("star_Loader.lottie")).value,
                        iterations = LottieConstants.IterateForever,
                        modifier = Modifier.size(200.dp)
                    )
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NewPostTopBar(onSendClick: () -> Unit = {}) {
    val AppColors = LocalAppTheme.current

    var uploading by remember { mutableStateOf(false) }
    var lastBackClickTime by remember { mutableStateOf(0L) }
    var lastSendClickTime by remember { mutableStateOf(0L) }
    var showDraftBox by remember { mutableStateOf(false) }
    val debounceTime = 500L // 500毫秒防抖时间
    // 上传进度
    if (uploading) {
        BasicAlertDialog(
            onDismissRequest = { },
        ) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .clip(RoundedCornerShape(64.dp)).shadow(elevation = 4.dp)
                    .background(AppColors.background).padding(16.dp),
                contentAlignment = Alignment.CenterStart
            ) {
                CircularProgressIndicator(
                    modifier = Modifier.size(24.dp),
                    color = AppColors.main
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text("Uploading", modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, color = AppColors.text)
            }
        }
    }
    val navController = LocalNavController.current
    val context = LocalContext.current
    val model = NewPostViewModel
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 18.dp, vertical = 10.dp)
    ) {
        Row(
            modifier = Modifier.align(Alignment.CenterStart),
        ) {
            Image(
                painter = painterResource(id = R.drawable.rider_pro_back_icon),
                contentDescription = "Back",
                modifier = Modifier
                    .size(24.dp)
                    .noRippleClickable {
                        // 添加防抖逻辑
                        val currentTime = System.currentTimeMillis()
                        if (currentTime - lastSendClickTime > debounceTime) {
                            lastSendClickTime = currentTime
                            // 保存草稿后再返回
                            model.saveDraft(context)
                            navController.popBackStack()
                        }
                    },
                colorFilter = ColorFilter.tint(AppColors.text)
            )
            Spacer(modifier = Modifier.width(8.dp))
            Text(
                modifier = Modifier.align(Alignment.CenterVertically),
                text = stringResource(R.string.publish_dynamic),
                fontSize = 17.sp,
                color = AppColors.text,
            )
            Spacer(modifier = Modifier.weight(1f))
            Image(
                painter = painterResource(id = R.mipmap.icon_draft_box_light),
                contentDescription = "",
                modifier = Modifier
                    .size(24.dp)
                    .noRippleClickable {
                        // 添加防抖逻辑
                        val currentTime = System.currentTimeMillis()
                        if (currentTime - lastSendClickTime > debounceTime) {
                            lastSendClickTime = currentTime
                            showDraftBox = true
                        }
                    },
                colorFilter = ColorFilter.tint(AppColors.text)
            )
            Spacer(modifier = Modifier.width(20.dp))
            Image(
                painter = painterResource(id = R.mipmap.icon_released_light),
                contentDescription = "Send",
                modifier = Modifier
                    .size(24.dp)
                    .noRippleClickable {
                        // 检查输入
                        val errorMessage = model.validateMoment(context)
                        if (errorMessage != null) {
                            Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show()
                            return@noRippleClickable
                        }
                        model.viewModelScope.launch {
                            try {
                                uploading = true
                                model.createMoment(context = context) { progress ->
                                    // 更新进度条
                                }
                                // 发布成功后清空内容
                                model.asNewPost()
                                navController.popBackStack()
                            }catch (e:Exception) {
                                e.printStackTrace()
                            }finally {
                                uploading = false
                            }
                        }
                    },
            )
        }

    }
    
    // 草稿箱弹窗
    if (showDraftBox) {
        DraftBoxBottomSheet(
            onDismiss = { showDraftBox = false }
        )
    }
}

@Composable
fun NewPostTextField(hint: String, value: String, onValueChange: (String) -> Unit) {
    val AppColors = LocalAppTheme.current

    Box(modifier = Modifier.fillMaxWidth()) {
        BasicTextField(
            value = value,
            onValueChange = onValueChange,
            modifier = Modifier
                .fillMaxWidth()
                .height(160.dp)
                .heightIn(160.dp)
                .padding(horizontal = 16.dp, vertical = 10.dp),
            cursorBrush = SolidColor(AppColors.text),
            textStyle = TextStyle(
                lineHeight = 24.sp,
                color = AppColors.text,

            ),

        )
        if (value.isEmpty()) {
            Text(
                text = hint,
                color = AppColors.inputHint,
                modifier = Modifier.padding(horizontal = 18.dp, vertical = 10.dp)
            )
        }
    }
}


@Composable
fun AddImageGrid() {
    val AppColors = LocalAppTheme.current
    val navController = LocalNavController.current
    val context = LocalContext.current
    val model = NewPostViewModel
    val scope = model.viewModelScope
    val pickImagesLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetMultipleContents()
    ) { uris ->
        if (uris.isNotEmpty()) {
            scope.launch {
                val currentCount = model.imageList.size
                val remainingSlots = 9 - currentCount

                if (remainingSlots <= 0) {
                    Toast.makeText(context, "最多只能选择9张图片", Toast.LENGTH_SHORT).show()
                    return@launch
                }

                val urisToProcess = if (uris.size > remainingSlots) {
                    Toast.makeText(context, "已选择${uris.size}张图片，但只能添加前${remainingSlots}张", Toast.LENGTH_SHORT).show()
                    uris.take(remainingSlots)
                } else {
                    uris
                }

                for (uri in urisToProcess) {
                    ImageItem.fromUri(context, uri.toString())?.let {
                        model.imageList += it
                    }
                }
            }
        }
    }

    val takePictureLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.TakePicture()
    ) { success ->
        if (success) {
            scope.launch {
                if (model.imageList.size >= 9) {
                    Toast.makeText(context, "最多只能选择9张图片", Toast.LENGTH_SHORT).show()
                    return@launch
                }

                ImageItem.fromUri(context, model.currentPhotoUri.toString())?.let {
                    model.imageList += it
                }
            }
        }
    }

    // 摄像头权限请求
    val requestCameraPermissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (isGranted) {
            // 权限已授予，打开相机
            if (model.imageList.size < 9) {
                val photoFile = File(context.cacheDir, "photo.jpg")
                val photoUri: Uri = FileProvider.getUriForFile(
                    context,
                    "${context.packageName}.fileprovider",
                    photoFile
                )
                model.currentPhotoUri = photoUri
                takePictureLauncher.launch(photoUri)
            } else {
                Toast.makeText(context, "最多只能选择9张图片", Toast.LENGTH_SHORT).show()
            }
        } else {
            // 权限被拒绝，提示用户
            Toast.makeText(
                context,
                "需要摄像头权限才能拍摄照片，请在设置中开启",
                Toast.LENGTH_LONG
            ).show()
        }
    }

    val addImageDebouncer = rememberDebouncer()
    val canAddMoreImages = model.imageList.size < 9

    LazyVerticalGrid(
        columns = GridCells.Fixed(5),
        contentPadding = PaddingValues(horizontal = 19.dp, vertical = 4.dp),
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        // 添加按钮
        if (canAddMoreImages) {
            item {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .aspectRatio(1f)
                        .clip(RoundedCornerShape(24.dp))
                        .background(Color(0xFFFAF9FB))
                        .noRippleClickable {
                            addImageDebouncer {
                                if (model.imageList.size < 9) {
                                    pickImagesLauncher.launch("image/*")
                                } else {
                                    Toast.makeText(
                                        context,
                                        "最多只能选择9张图片",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                }
                            }
                        },
                ) {
                    Icon(
                        painter = painterResource(id = R.drawable.rider_pro_new_post_add_pic),
                        contentDescription = "Add Image",
                        modifier = Modifier
                            .size(23.3.dp)
                            .align(Alignment.Center),
                        tint = AppColors.nonActiveText
                    )
                }
            }
            
            // 相机按钮
            item {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .aspectRatio(1f)
                        .clip(RoundedCornerShape(24.dp))
                        .background(Color(0xFFFAF9FB))
                        .noRippleClickable {
                            if (model.imageList.size < 9) {
                                // 检查摄像头权限
                                when {
                                    ContextCompat.checkSelfPermission(
                                        context,
                                        Manifest.permission.CAMERA
                                    ) == PackageManager.PERMISSION_GRANTED -> {
                                        // 已有权限，直接打开相机
                                        val photoFile = File(context.cacheDir, "photo.jpg")
                                        val photoUri: Uri = FileProvider.getUriForFile(
                                            context,
                                            "${context.packageName}.fileprovider",
                                            photoFile
                                        )
                                        model.currentPhotoUri = photoUri
                                        takePictureLauncher.launch(photoUri)
                                    }
                                    else -> {
                                        // 没有权限，请求权限
                                        requestCameraPermissionLauncher.launch(Manifest.permission.CAMERA)
                                    }
                                }
                            } else {
                                Toast.makeText(context, "最多只能选择9张图片", Toast.LENGTH_SHORT).show()
                            }
                        },
                ) {
                    Icon(
                        painter = painterResource(id = R.drawable.rider_pro_camera),
                        contentDescription = "Take Photo",
                        modifier = Modifier
                            .size(23.3.dp)
                            .align(Alignment.Center),
                        tint = AppColors.nonActiveText
                    )
                }
            }
        }
        
        // 已添加的图片，显示在相机按钮后面
        items(model.imageList.size) { index ->
            val item = model.imageList[index]
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(1f)
                    .clip(RoundedCornerShape(24.dp))
                    .background(Color(0xFFFAF9FB))
            ) {
                CustomAsyncImage(
                    context,
                    item.bitmap,
                    contentDescription = "Image",
                    modifier = Modifier
                        .fillMaxSize()
                        .noRippleClickable {
                            navController.navigate(NavigationRoute.NewPostImageGrid.route)
                        },
                    contentScale = ContentScale.Crop
                )
                
//                // 删除按钮 - 右上角
//                Box(
//                    modifier = Modifier
//                        .align(Alignment.TopEnd)
//                        .padding(4.dp)
//                        .size(20.dp)
//                        .clip(RoundedCornerShape(10.dp))
//                        .background(Color.Black.copy(alpha = 0.6f))
//                        .noRippleClickable {
//                            model.imageList = model.imageList.toMutableList().apply {
//                                removeAt(index)
//                            }
//                        },
//                    contentAlignment = Alignment.Center
//                ) {
//                    Icon(
//                        painter = painterResource(id = R.drawable.rider_pro_close),
//                        contentDescription = "Delete",
//                        modifier = Modifier.size(12.dp),
//                        tint = Color.White
//                    )
//                }
            }
        }
    }
}

