package com.aiosman.ravenow.ui.post

import android.net.Uri
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
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.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.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.platform.LocalContext
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.tooling.preview.Preview
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

/**
 * 发布动态
 */
@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) }
    val keyboardController = LocalSoftwareKeyboardController.current

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


    StatusBarMaskLayout(
        darkIcons = !AppState.darkMode,
        modifier = Modifier
            .fillMaxSize()
            .background(
                AppColors.background
            )
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(AppColors.background)
        ) {
            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) {
                NewPostViewModel.textContent = it
            }
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(1.dp)
                    .background(AppColors.divider)
            )
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 8.dp, start = 16.dp, end = 16.dp, bottom = 8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Image(
                    painter = painterResource(id = R.mipmap.rider_pro_moment_ai),
                    contentDescription = null,
                    modifier = Modifier
                        .size(24.dp)

                )
                Text(
                    text = stringResource(R.string.moment_ai_co),
                    fontWeight = FontWeight.Bold,
                    fontSize = 15.sp,
                    modifier = Modifier
                        .padding(start = 8.dp)
                        .weight(1f),
                    color = AppColors.text,
                )
                Switch(
                    checked = isAiEnabled,
                    onCheckedChange = {
                            isChecked ->
                        isAiEnabled = isChecked
                        if (isChecked) {
                            // 收起键盘
                            keyboardController?.hide()
                            isRequesting = true
                            isRotating = true
                            model.viewModelScope.launch {
                                try {
                                    model.agentMoment(model.textContent)
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }finally {
                                    isRequesting = false
                                    isRotating = false
                                    isAiEnabled = false
                                }
                            }

                        } else {

                        }
                    },
                    enabled = !isRequesting && model.textContent.isNotEmpty(),
                    colors = SwitchDefaults.colors(
                        checkedThumbColor = Color.White,
                        checkedTrackColor = AppColors.brandColorsColor,
                        uncheckedThumbColor = Color.White,
                        uncheckedTrackColor = AppColors.nonActive,
                        uncheckedBorderColor = Color.White,
                        disabledCheckedTrackColor = AppColors.brandColorsColor.copy(alpha = 0.8f),
                        disabledCheckedThumbColor= Color.White,
                        disabledUncheckedTrackColor = AppColors.nonActive,
                        disabledUncheckedThumbColor= Color.White

                    ),
                    modifier = Modifier.scale(0.8f)

                )
            }

            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)
                            )
                        }
                    }
                }
            }

        }
    }
}

@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) }
    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_close),
                contentDescription = "Back",
                modifier = Modifier
                    .size(24.dp)
                    .noRippleClickable {
                        // 添加防抖逻辑
                        val currentTime = System.currentTimeMillis()
                        if (currentTime - lastSendClickTime > debounceTime) {
                            lastSendClickTime = currentTime
                            navController.popBackStack()
                        }
                    },
                colorFilter = ColorFilter.tint(AppColors.text)
            )
            Spacer(modifier = Modifier.weight(1f))
            Image(
                painter = painterResource(id = R.mipmap.rider_pro_moment_post),
                contentDescription = "Send",
                modifier = Modifier
                    .size(24.dp)
                    .noRippleClickable {
                        // 检查输入
                        val errorMessage = model.validateMoment()
                        if (errorMessage != null) {
                            Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show()
                            return@noRippleClickable
                        }
                        model.viewModelScope.launch {
                            try {
                                uploading = true
                                model.createMoment(context = context) { progress ->
                                    // 更新进度条
                                }
                                navController.popBackStack()
                            }catch (e:Exception) {
                                e.printStackTrace()
                            }finally {
                                uploading = 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 addImageDebouncer = rememberDebouncer()
    val takePhotoDebouncer = rememberDebouncer()

    val stroke = Stroke(
        width = 2f,
        pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f)
    )
    DraggableGrid(
        items = NewPostViewModel.imageList,
        onMove = { from, to ->
            NewPostViewModel.imageList = NewPostViewModel.imageList.toMutableList().apply {
                add(to, removeAt(from))
            }
        },
        lockedIndices = listOf(

        ),
        onDragModeEnd = {},
        onDragModeStart = {},
        additionalItems = listOf(

        ),
        getItemId = { it.id }
    ) { item, isDrag ->
        Box(
            modifier = Modifier
        ) {
            CustomAsyncImage(
                LocalContext.current,
                item.bitmap,
                contentDescription = "Image",
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(1f)
                    .noRippleClickable {
                        navController.navigate(NavigationRoute.NewPostImageGrid.route)
                    },
                contentScale = ContentScale.Crop
            )
            if (isDrag) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(Color.Black.copy(alpha = 0.4f))
                )
            }
        }
    }
    val canAddMoreImages = model.imageList.size < 9

    LazyVerticalGrid(
        columns = GridCells.Fixed(5),
        contentPadding = PaddingValues(8.dp),
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        if (canAddMoreImages) {
            item {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .aspectRatio(1f)
                        .clip(RoundedCornerShape(16.dp)) // 设置圆角
                        .background(AppColors.basicMain) // 设置背景色
                        .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(24.dp)
                            .align(Alignment.Center),
                        tint = AppColors.nonActiveText

                    )
                }
            }
            item {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .aspectRatio(1f)
                        .clip(RoundedCornerShape(16.dp)) // 设置圆角
                        .background(AppColors.basicMain) // 设置背景色
                        .noRippleClickable {
                            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()
                            }
                        },
                ) {
                    Icon(
                        painter = painterResource(id = R.drawable.rider_pro_camera),
                        contentDescription = "Take Photo",
                        modifier = Modifier
                            .size(24.dp)
                            .align(Alignment.Center),
                        tint = AppColors.nonActiveText
                    )
                }
            }
        }
    }
}

