package com.example.dtf.screens

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ThumbUp
import androidx.compose.runtime.Composable
import androidx.compose.runtime.*
import androidx.compose.ui.*
import androidx.compose.ui.draw.*
import androidx.compose.ui.geometry.*
import androidx.compose.ui.graphics.*
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.*
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import androidx.paging.PagingData
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.example.dtf.PreferencesManager
import com.example.dtf.models.Category
import com.example.dtf.models.Post
import com.example.dtf.utils.ScreenPaths
import com.example.dtf.viewmodels.PostsViewModel
import kotlinx.coroutines.flow.Flow

@Composable
fun PostsScreen(navController: NavHostController) {
    val sharedPref = PreferencesManager(LocalContext.current)

    val currentCategory = remember { mutableStateOf<Category?>(null) }

    val viewModel = hiltViewModel<PostsViewModel>()
    val posts = remember { mutableStateOf<Flow<PagingData<Post>>?>(null) }

    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.spacedBy(10.dp)
    ) {

        Categories(viewModel, currentCategory, posts)
        Row(
            modifier = Modifier.fillMaxSize()
        ) {
            if (currentCategory.value != null && posts.value != null) {
                PostsByCategory(viewModel, navController, posts)
            }
        }
    }
}

@Composable
private fun Categories(viewModel: PostsViewModel, currentCategory: MutableState<Category?>, posts: MutableState<Flow<PagingData<Post>>?>) {
    val categories = viewModel.getCategoriesListUiState().collectAsLazyPagingItems()


    LazyRow(
        modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight(0.1f)
            .background(Color.White),
        horizontalArrangement = Arrangement.spacedBy(25.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        item {
            Spacer(modifier = Modifier.width(5.dp))
        }
        items(
            count = categories.itemCount,
            key = categories.itemKey()
        ) {
            if (currentCategory.value == null) {
                currentCategory.value = categories[0]
                posts.value = viewModel.getPostsListUiState(currentCategory.value!!.id!!)
            }
            Text(
                modifier = Modifier
                    .clickable {
                        currentCategory.value = categories[it]!!
                        posts.value = viewModel.getPostsListUiState(categories[it]!!.id!!)
                    }
                    .drawBehind {
                        if (categories[it]!!.name == currentCategory.value?.name) {
                            val strokeWidthPx = 2.dp.toPx()
                            val verticalOffset = size.height + 2.sp.toPx()
                            drawLine(
                                color = Color(0xFF319CFF),
                                strokeWidth = strokeWidthPx,
                                start = Offset(0f, verticalOffset),
                                end = Offset(size.width, verticalOffset)
                            )
                        }
                    },
                text = categories[it]!!.name,
                fontSize = 22.sp
            )
        }
    }
}

@Composable
private fun PostsByCategory(viewModel: PostsViewModel, navController: NavHostController, posts: MutableState<Flow<PagingData<Post>>?>) {
    val postsItems = posts.value!!.collectAsLazyPagingItems()

    LazyColumn(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.spacedBy(10.dp)
    ) {
        items(
            count = postsItems.itemCount,
            key = postsItems.itemKey()
        ) {
            Post(viewModel, navController, postsItems[it]!!)
        }
        item {
            Spacer(modifier = Modifier.height(60.dp))
        }
    }
}

@Composable
private fun Post(viewModel: PostsViewModel, navController: NavHostController, post: Post) {
    val sharedPref = PreferencesManager(LocalContext.current)

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

    LaunchedEffect(Unit) {
        viewModel.getLikes(post.id!!).collect {
            likes.intValue = it
        }
    }

    LaunchedEffect(Unit) {
        viewModel.isLiked(sharedPref, post.id!!).collect {
            isLiked.value = it
        }
    }

    Column(
        modifier = Modifier
            .fillMaxHeight(0.3f)
            .heightIn(max = 250.dp)
            .fillMaxWidth()
            .background(Color.White)
            .clickable {
                navController.navigate(ScreenPaths.Post.route.replace("{post}", post.id.toString()))
            },
        verticalArrangement = Arrangement.spacedBy(5.dp),
        horizontalAlignment = Alignment.Start
    ) {
        Text(
            modifier = Modifier.padding(10.dp),
            text = post.title,
            fontSize = 26.sp
        )
        Text(
            modifier = Modifier
                .fillMaxHeight(0.6f)
                .padding(10.dp, 0.dp, 10.dp, 0.dp),
            text = post.content,
            fontSize = 20.sp,
            overflow = TextOverflow.Ellipsis
        )
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(10.dp),
            verticalAlignment = Alignment.Bottom,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text(
                text = post.date,
                fontSize = 14.sp,
                color = Color(0xFFCECCCC)
            )
            Row (
                modifier = Modifier
                    .fillMaxWidth(),
                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, post.id!!)
                                likes.intValue--
                            } else {
                                viewModel.likePost(sharedPref, post.id!!)
                                likes.intValue++
                            }
                            isLiked.value = !isLiked.value
                        },
                    imageVector = Icons.Default.ThumbUp,
                    contentDescription = null,
                    tint = if (isLiked.value) { Color(40, 200, 40, 255) } else {Color.Black}
                )
            }
        }
    }
}