package com.example.pmulabs.screensMobile

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.requiredWidth
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
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.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import com.example.pmulabs.basecomponents.navigate.ARTICLE_ARGUMENT_KEY
import com.example.pmulabs.basecomponents.navigate.BottomBarScreen
import com.example.pmulabs.designElem.elem.BackButton
import com.example.pmulabs.designElem.items.CommentItem
import com.example.pmulabs.room.models.Article
import com.example.pmulabs.room.models.Comment
import com.example.pmulabs.room.models.Tag
import com.example.pmulabs.viewModels.AppViewModelProvider
import com.example.pmulabs.viewModels.ArticlePageScreenViewModel
import com.example.pmulabs.viewModels.CurrentUserViewModel
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date

@SuppressLint("UnrememberedMutableState")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ArticlePageScreen(navController: NavController, modifier: Modifier = Modifier,articlePageScreenViewModel: ArticlePageScreenViewModel= viewModel(factory = AppViewModelProvider.Factory), currentUserViewModel: CurrentUserViewModel = viewModel(factory = AppViewModelProvider.Factory)) {

    var id =
        navController.currentBackStackEntry?.arguments?.getString(ARTICLE_ARGUMENT_KEY).toString()
    try {
        articlePageScreenViewModel.getArticleById(id.toInt())
    } catch (e: NumberFormatException) {
        e.printStackTrace()
    }
    var textComm by rememberSaveable { mutableStateOf("") }
    var article by mutableStateOf<Article?>(articlePageScreenViewModel.article)

    try {
        article?.tagId?.let { articlePageScreenViewModel.getTagById(it) }
    } catch (e: Exception) {
        e.printStackTrace()
    }
    var tag by mutableStateOf<Tag?>(articlePageScreenViewModel.tag)
    Log.d("Tag:", tag.toString())
    var tagId = articlePageScreenViewModel.tag?.id

    val formatter = SimpleDateFormat("dd.MM.YY")
    val publishDate = formatter.format(Date(article?.publishDate ?: 0))

    val comms = articlePageScreenViewModel.comments.collectAsLazyPagingItems()

    var getUser by remember { mutableStateOf(currentUserViewModel.user) }
    val coroutineScope = rememberCoroutineScope()

    LazyColumn(
        contentPadding = PaddingValues(top = 105.dp, bottom = 50.dp, start = 15.dp, end = 15.dp),
        modifier = modifier
            .requiredWidth(width = 412.dp)
            .requiredHeight(height = 915.dp)
            .background(color = Color.White)
            .fillMaxSize(),
        verticalArrangement = Arrangement.spacedBy(1.dp)
    ) {
        item {
            BackButton(modifier = Modifier
                .clickable { navController.navigate(BottomBarScreen.Main.route) }
                .offset(
                    y = 0.dp
                ))
        }
        item {
            Row(
                modifier = Modifier
                    .requiredWidth(width = 350.dp)
                    .requiredHeight(height = 33.dp)
                    .offset(
                        y = 0.dp
                    )
            ) {
                Text(
                    text = "${publishDate}",
                    color = Color(0xff423a99),
                    style = MaterialTheme.typography.headlineMedium
                )
                Text(
                    text = "#${tag?.title}",
                    color = Color(0xff423a99),
                    style = MaterialTheme.typography.headlineMedium,
                    modifier = Modifier
                        .offset(
                            x = 20.dp,
                            y = 0.dp
                        )
                )
            }
        }
        item {
            Text(
                text = "${article?.title}",
                color = Color(0xff423a99),
                style = TextStyle(
                    fontSize = 32.sp,
                    fontWeight = FontWeight.Bold
                ),
                modifier = Modifier
                    .offset(
                        x = 10.dp,
                        y = 0.dp
                    )
                    .requiredWidth(width = 395.dp)
            )

        }
        item {
            Text(
                text = "${article?.text}",
                color = Color(0xff423a99),
                style = MaterialTheme.typography.headlineMedium,
                modifier = Modifier
                    .offset(
                        x = 5.dp,
                        y = 0.dp
                    )
                    .requiredWidth(width = 375.dp)
            )
        }
        item {
            Box(
                modifier = modifier
                    .requiredWidth(width = 412.dp)
                    .requiredHeight(height = 53.dp)
                    .offset(
                        y = 0.dp
                    )
            ) {
                Text(
                    text = "Comments:",
                    color = Color(0xff423a99),
                    style = TextStyle(
                        fontSize = 32.sp,
                        fontWeight = FontWeight.Bold
                    ),
                    modifier = Modifier
                        .align(alignment = Alignment.TopStart)
                        .offset(
                            x = 15.dp,
                            y = 6.dp
                        )
                        .requiredWidth(width = 395.dp)
                        .requiredHeight(height = 43.dp)
                )
                HorizontalDivider(
                    thickness = 5.dp,
                    modifier = Modifier
                        .border(BorderStroke(3.dp, Color(0xff423a99))), color = Color(0xff423a99)
                )
                HorizontalDivider(
                    thickness = 5.dp,
                    modifier = Modifier
                        .align(alignment = Alignment.TopStart)
                        .border(BorderStroke(3.dp, Color(0xff423a99)))
                        .offset(
                            y = 53.dp
                        ), color = Color(0xff423a99)
                )
            }
        }
        item {
            OutlinedTextField(
                value = textComm,
                onValueChange = {
                    textComm = it
                },
                colors = TextFieldDefaults.textFieldColors(
                    containerColor = Color.White,
                    focusedIndicatorColor = Color(0xff423a99),
                    focusedLabelColor = Color(0xff423a99),
                    unfocusedIndicatorColor = Color(0xff423a99),
                    unfocusedLabelColor = Color(0xff423a99)
                ),
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight()
                    .padding(10.dp),
                label = { Text("Comment") },
                placeholder = { Text("Write comment...") },
                minLines = 3,
                maxLines = 3,
            )
            Button(
                colors = ButtonColors(
                    containerColor = Color(0xff423a99),
                    disabledContainerColor = Color(0xff423a99),
                    contentColor = Color.White,
                    disabledContentColor = Color.White
                ),
                onClick = {
                    if (textComm.isNotEmpty()) {
                        var newComment =
                            Comment(null, textComm, getUser?.id.toString().toInt(), id.toInt())
                        coroutineScope.launch {
                            articlePageScreenViewModel.insertComment(newComment)
                        }
                        textComm = ""
                        navController.navigate(BottomBarScreen.ArticlePage.passId(article?.id.toString()))
                    }
                },
                modifier = Modifier
                    .padding(start = 230.dp)
                    .fillMaxWidth(0.9f)
                    .height(40.dp)
            ) {
                Text(text = "Send", fontSize = 20.sp)
            }
        }

        items(count = comms.itemCount) { index ->
            val comm = comms[index]
            if (comm != null) {
                if (comm.articleId == article?.id && comm.text != "") {
                    Spacer(modifier = Modifier.padding(0.dp))
                    HorizontalDivider(
                        thickness = 3.dp,
                        modifier = Modifier
                            .border(BorderStroke(3.dp, Color(0xff423a99))), color = Color(0xff423a99)
                    )
                    CommentItem(navController,comm = comm, currentUserViewModel = currentUserViewModel)
                }
            }
        }
        comms.apply {
            when {
                loadState.refresh is LoadState.Loading -> {
                    item {
                        CircularProgressIndicator(
                            modifier = Modifier.fillParentMaxSize(),
                            color = Color(0xff423a99)
                        )
                    }
                }

                loadState.append is LoadState.Loading -> {
                    item {
                        CircularProgressIndicator(
                            modifier = Modifier.fillParentMaxSize(),
                            color = Color(0xff423a99)
                        )
                    }
                }

                loadState.refresh is LoadState.Error -> {
                    val err = comms.loadState.refresh as LoadState.Error
                    item { Text(err.error.localizedMessage) }
                }

                loadState.append is LoadState.Error -> {
                    val err = comms.loadState.append as LoadState.Error
                    item { Text(err.error.localizedMessage) }
                }
            }
        }

    }
}
