package com.aiosman.riderpro.ui.comment

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.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
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.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import com.aiosman.riderpro.R
import com.aiosman.riderpro.entity.CommentEntity
import com.aiosman.riderpro.ui.composables.EditCommentBottomModal
import com.aiosman.riderpro.ui.post.CommentContent
import com.aiosman.riderpro.ui.post.CommentMenuModal
import com.aiosman.riderpro.ui.post.CommentsViewModel
import com.aiosman.riderpro.ui.post.OrderSelectionComponent
import kotlinx.coroutines.launch

/**
 * 评论弹窗的 ViewModel
 */
class CommentModalViewModel(
    val postId: Int?
) : ViewModel() {
    var commentText by mutableStateOf("")
    var commentsViewModel: CommentsViewModel = CommentsViewModel(postId.toString())
    init {
        commentsViewModel.preTransit()
    }


}


/**
 * 评论弹窗
 * @param postId 帖子ID
 * @param onCommentAdded 评论添加回调
 * @param onDismiss 关闭回调
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CommentModalContent(
    postId: Int? = null,
    commentCount: Int = 0,
    onCommentAdded: () -> Unit = {},
    onDismiss: () -> Unit = {}
) {
    val model = viewModel<CommentModalViewModel>(
        key = "CommentModalViewModel_$postId",
        factory = object : ViewModelProvider.Factory {
            override fun <T : ViewModel> create(modelClass: Class<T>): T {
                return CommentModalViewModel(postId) as T
            }
        }
    )
    val commentViewModel = model.commentsViewModel
    var navBarHeight = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()
    LaunchedEffect(Unit) {

    }
    var showCommentMenu by remember { mutableStateOf(false) }
    var contextComment by remember { mutableStateOf<CommentEntity?>(null) }
    val insets = WindowInsets
    val imePadding = insets.ime.getBottom(density = LocalDensity.current)
    var bottomPadding by remember { mutableStateOf(0.dp) }
    var softwareKeyboardController = LocalSoftwareKeyboardController.current
    var replyComment by remember { mutableStateOf<CommentEntity?>(null) }

    LaunchedEffect(imePadding) {
        bottomPadding = imePadding.dp
    }
    DisposableEffect(Unit) {
        onDispose {
            onDismiss()
        }
    }
    if (showCommentMenu) {
        ModalBottomSheet(
            onDismissRequest = {
                showCommentMenu = false
            },
            containerColor = Color.White,
            sheetState = rememberModalBottomSheetState(
                skipPartiallyExpanded = true
            ),
            dragHandle = {},
            shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
            windowInsets = WindowInsets(0)
        ) {
            CommentMenuModal(
                onDeleteClick = {
                    showCommentMenu = false
                    contextComment?.let {
                        commentViewModel.deleteComment(it.id)
                    }
                }
            )
        }
    }
    suspend fun sendComment() {
        if (model.commentText.isNotEmpty()) {
            softwareKeyboardController?.hide()
            commentViewModel.createComment(
                model.commentText,
            )
        }
        onCommentAdded()
    }
    Column(
        modifier = Modifier
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(start = 16.dp, bottom = 16.dp, end = 16.dp)

        ) {
            Text(
                stringResource(R.string.comment),
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.align(Alignment.Center)
            )
        }

        HorizontalDivider(
            color = Color(0xFFF7F7F7)
        )
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 24.dp, vertical = 16.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text(
                text = stringResource(id = R.string.comment_count, commentCount),
                fontSize = 14.sp,
                color = Color(0xff666666)
            )
            OrderSelectionComponent {
                commentViewModel.order = it
                commentViewModel.reloadComment()
            }
        }
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp)
                .weight(1f)
        ) {
            LazyColumn(
                modifier = Modifier
                    .fillMaxWidth()
            ) {
                item {
                    CommentContent(
                        viewModel = commentViewModel,
                        onLongClick = { commentEntity: CommentEntity ->

                        },
                        onReply = { parentComment, _, _, _ ->

                        },
                    )
                    Spacer(modifier = Modifier.height(72.dp))
                }

            }
        }
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .background(Color(0xfff7f7f7))
        ) {
            EditCommentBottomModal(replyComment) {
                commentViewModel.viewModelScope.launch {
                    if (replyComment != null) {
                        if (replyComment?.parentCommentId != null) {
                            // 第三级评论
                            commentViewModel.createComment(
                                it,
                                parentCommentId = replyComment?.parentCommentId,
                                replyUserId = replyComment?.author?.toInt()
                            )
                        } else {
                            // 子级评论
                            commentViewModel.createComment(it, replyComment?.id)
                        }
                    } else {
                        // 顶级评论
                        commentViewModel.createComment(it)
                    }
                }

            }
            Spacer(modifier = Modifier.height(navBarHeight))

        }


    }

}


