package com.example.pmulabs.screensMobile

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.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.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
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.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
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.BottomBarScreen
import com.example.pmulabs.designElem.items.TagItem
import com.example.pmulabs.room.models.Tag
import com.example.pmulabs.viewModels.AppViewModelProvider
import com.example.pmulabs.viewModels.CurrentUserViewModel
import com.example.pmulabs.viewModels.TagItemViewModel
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TagsScreen(navController: NavController, modifier: Modifier = Modifier, tagItemViewModel: TagItemViewModel = viewModel(factory = AppViewModelProvider.Factory), currentUserViewModel: CurrentUserViewModel = viewModel(factory = AppViewModelProvider.Factory)){

    var tags = tagItemViewModel.tags.collectAsLazyPagingItems()

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

    if (openDialog) {
        AlertDialog(
            onDismissRequest = {
                openDialog = false
                text = ""
            },
            content = {
                Column(
                    modifier = Modifier
                        .clip(RoundedCornerShape(16.dp))
                        .background(Color.White)
                        .padding(16.dp),
                ) {
                    Text(
                        text = "Add your tag",
                        color = Color(0xff423a99),
                        style = TextStyle(
                            fontSize = 20.sp,
                        ),
                    )
                    OutlinedTextField(
                        value = text,
                        onValueChange = {
                            text = 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("Tag") },
                        placeholder = { Text("Write tag...") },
                        minLines = 3,
                        maxLines = 3,
                    )
                    Row(
                        modifier = Modifier.padding(all = 8.dp),
                        horizontalArrangement = Arrangement.Center
                    ) {
                        Button(
                            colors = ButtonColors(
                                containerColor = Color(0xff423a99),
                                disabledContainerColor = Color(0xff423a99),
                                contentColor = Color.White,
                                disabledContentColor = Color.White
                            ),
                            onClick = {
                                openDialog = false
                                if(text.isNotEmpty()) {
                                    val newTag = Tag(null, text, getUser?.id.toString().toInt())
                                    coroutineScope.launch {
                                        tagItemViewModel.insertTag(newTag)
                                    }
                                    navController.navigate(BottomBarScreen.Categories.route)
                                }
                            },
                            modifier = Modifier
                                .padding(start = 100.dp)
                                .fillMaxWidth(0.5f)
                                .height(40.dp)
                        ) {
                            Text(text = "Add", fontSize = 20.sp)
                        }
                    }
                }
            },
        )
    }

    LazyColumn(
        modifier= Modifier
            .background(Color.White)
            .fillMaxSize(),
        contentPadding = PaddingValues(top =75.dp, bottom = 10.dp, start = 25.dp,end=25.dp),
        verticalArrangement = Arrangement.spacedBy(15.dp)){
        item{
            Box(
                modifier = modifier
                    .requiredWidth(width = 365.dp)
                    .requiredHeight(height = 58.dp)
            ) {
                Box(
                    modifier = Modifier
                        .requiredWidth(width = 365.dp)
                        .requiredHeight(height = 58.dp)
                        .clip(shape = RoundedCornerShape(15.dp))
                        .background(color = Color(0xff423a99))
                        .clickable { openDialog=true }
                )
                Text(
                    text = "Add Tag!",
                    color = Color(0xFFFFFFFF),
                    textAlign = TextAlign.Center,
                    style = TextStyle(
                        fontSize = 24.sp,
                        fontWeight = FontWeight.Bold
                    ),
                    modifier = Modifier

                        .offset(
                            x = 135.dp,
                            y = 14.dp
                        )
                )
            }
        }
        items(count = tags.itemCount) { index ->
            val tag = tags[index]
            if (tag != null) {
                TagItem(
                    navController=navController,
                    teg = tag,
                    viewModel = currentUserViewModel,
                    onTagClick = {navController.navigate(BottomBarScreen.SearchByTag.passId(tag?.id.toString()))}
                )
            }
        }
        tags.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 = tags.loadState.refresh as LoadState.Error
                    item { Text(err.error.localizedMessage) }
                }
                loadState.append is LoadState.Error -> {
                    val err = tags.loadState.append as LoadState.Error
                    item { Text(err.error.localizedMessage) }
                }
            }
        }
    }
}