package com.example.dtf.screens

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AddCircle
import androidx.compose.material.icons.filled.ThumbUp
import androidx.compose.runtime.Composable
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.*
import androidx.compose.ui.draw.*
import androidx.compose.ui.graphics.*
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.*
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.example.dtf.PreferencesManager
import com.example.dtf.models.Comment
import com.example.dtf.utils.ScreenPaths
import com.example.dtf.viewmodels.PostViewModel
import com.example.dtf.widgets.MyTextField

@Composable
fun PostScreen(postId: Int, navController: NavHostController) {
    val sharedPref = PreferencesManager(LocalContext.current)

    val viewModel = hiltViewModel<PostViewModel>()
    val post = viewModel.post.observeAsState().value
    val comments = viewModel.getCommentsListUiState(postId).collectAsLazyPagingItems()

    val likes = remember { mutableIntStateOf(0) }
    val isLiked = remember { mutableStateOf(false) }

    LaunchedEffect(Unit) {
        viewModel.getLikes(postId).collect {
            likes.intValue = it
        }
    }

    LaunchedEffect(Unit) {
        viewModel.isLiked(sharedPref, postId).collect {
            isLiked.value = it
        }
    }

    viewModel.retrievePost(postId)

    val content = remember { mutableStateOf(TextFieldValue("")) }

    LazyColumn(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.White),
        verticalArrangement = Arrangement.spacedBy(5.dp),
        horizontalAlignment = Alignment.Start
    ) {
        item {
            Text(
                modifier = Modifier.padding(10.dp),
                text = post?.title ?: "Loading...",
                fontSize = 26.sp
            )
            Text(
                modifier = Modifier.fillMaxHeight().padding(10.dp, 0.dp, 10.dp, 0.dp),
                text = post?.content ?: "Loading...",
                fontSize = 20.sp
            )
            Row(
                modifier = Modifier.fillMaxWidth().padding(10.dp),
                verticalAlignment = Alignment.Bottom,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                if (post != null) {
                    Text(
                        text = post.date,
                        fontSize = 14.sp,
                        color = Color(0xFFCECCCC)
                    )
                }

                if (sharedPref.getData("isModerator", "false").toBooleanStrict()) {
                    Text(
                        modifier = Modifier.clickable {
                            navController.navigate(ScreenPaths.EditPost.route.replace("{post}", postId.toString()))
                        },
                        text = "Изменить",
                        fontSize = 18.sp,
                        color = Color(0xFFAFAFAF)
                    )
                }
                Row (
                    modifier = Modifier,
                    horizontalArrangement = Arrangement.End
                ) {
                    Text(
                        text = likes.intValue.toString(),
                        fontSize = 16.sp,
                        color = Color.Green
                    )
                    Icon(
                        modifier = Modifier.padding(start = 8.dp).clickable {
                            if (isLiked.value) {
                                viewModel.unlikePost(sharedPref, postId)
                                likes.intValue--
                            } else {
                                viewModel.likePost(sharedPref, postId)
                                likes.intValue++
                            }
                            isLiked.value = !isLiked.value
                        },
                        imageVector = Icons.Default.ThumbUp,
                        contentDescription = null,
                        tint = if (isLiked.value) { Color(40, 200, 40, 255) } else {Color.Black}
                    )
                }
            }
            Divider()
            Text(
                modifier = Modifier.fillMaxWidth().padding(0.dp, 0.dp, 0.dp, 10.dp),
                text = "Комментарии",
                fontSize = 22.sp,
                textAlign = TextAlign.Center
            )
            Row(
                modifier = Modifier.fillMaxSize().padding(horizontal = 15.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                MyTextField(
                    value = content,
                    placeholder = "Комментарий",
                    onChanged = {content.value = it},
                    modifier = Modifier.fillMaxWidth(0.9f),
                    backgroundColor = Color.White
                )
                IconButton(
                    modifier = Modifier.fillMaxWidth().scale(1.5f),
                    onClick = {
                        viewModel.addComment(sharedPref, postId, content.value.text)
                        content.value = TextFieldValue("")
                    },
                ) {
                    Icon(
                        imageVector = Icons.Default.AddCircle,
                        contentDescription = null
                    )
                }
            }
        }
        items(
            comments.itemCount,
            key = comments.itemKey()
        ) {
            Comment(comments[it]!!)
        }
        item {
            Spacer(modifier = Modifier.height(60.dp))
        }
    }
}

@Composable
private fun Comment(comment: Comment) {
    val viewModel = hiltViewModel<PostViewModel>()
    val user = viewModel.getCommentsAuthor(comment).collectAsState(null).value

    Column(
        modifier = Modifier
                   .fillMaxWidth()
                   .padding(horizontal = 15.dp, vertical = 5.dp)
                   .border(width = 1.dp, color = Color(0xFFADADAD), shape = RoundedCornerShape(size = 10.dp))
                   .background(color = Color(0xFFFFFFFF), shape = RoundedCornerShape(size = 10.dp))
    ) {
        Row(
            modifier = Modifier.fillMaxWidth().padding(10.dp),
            verticalAlignment = Alignment.Top,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text(
                text = comment.author.ifEmpty { user?.username ?: "Loading..." },
                fontSize = 20.sp
            )
            Text(
                text = comment.date,
                fontSize = 14.sp,
                color = Color(0xFFCECCCC)
            )
        }
        Text(
            modifier = Modifier.padding(start = 10.dp, bottom = 5.dp),
            text = comment.content,
            fontSize = 16.sp
        )
    }
}