package com.example.pmulabs.designElem.items

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
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.Column
import androidx.compose.foundation.layout.Row
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.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.ArrowDropUp
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
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.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
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.compose.ui.unit.toSize
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.pmulabs.R
import com.example.pmulabs.basecomponents.navigate.BottomBarScreen
import com.example.pmulabs.room.models.Article
import com.example.pmulabs.room.models.Tag
import com.example.pmulabs.viewModels.AppViewModelProvider
import com.example.pmulabs.viewModels.ArticleItemViewModel
import com.example.pmulabs.viewModels.CurrentUserViewModel
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat

@SuppressLint("UnrememberedMutableState", "CoroutineCreationDuringComposition")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ArticleItem(navController: NavController,article: Article, modifier: Modifier = Modifier, onArticleClick: () -> Unit, articleItemViewModel: ArticleItemViewModel = viewModel(factory = AppViewModelProvider.Factory), currentUserViewModel: CurrentUserViewModel = viewModel(factory = AppViewModelProvider.Factory)) {

    val coroutineScope = rememberCoroutineScope()
    articleItemViewModel.setTagList()

    //список тэгов
    val tags = mutableStateOf<List<Tag>>(articleItemViewModel.tagList)

    //количество комментариев для статьи
    var countComm = remember{mutableStateOf<Int?>(0)}
    coroutineScope.launch {
        countComm.value = articleItemViewModel.getCount(article.id)
    }

    //текущий пользователь
    var getUser by remember { mutableStateOf(currentUserViewModel.user) }

    //формат даты
    val formatter = SimpleDateFormat("dd.MM.YY")
    val publishDate=formatter.format(article.publishDate)

    //список названий тэгов
    var tagName=""
    var tagsNames= remember { mutableStateListOf<String>() }
    tags.value.forEach{teg ->
        if(article.tagId == teg.id){
            tagName=teg.title
        }
        if(!tagsNames.contains(teg.title)) {
            tagsNames.add(teg.title)
        }
    }
    //открыто ли диалоговое окно
    var openDialog by remember { mutableStateOf(false) }

    //переменные article для update
    var text by remember { mutableStateOf(article.text) }
    var tagId by remember { mutableStateOf(article.tagId) }
    var title by remember { mutableStateOf(article.title) }

    //переменные для dropdown
    var expanded by remember { mutableStateOf(false) }
    val suggestions = tagsNames
    var selectedText by remember { mutableStateOf(tagName) }
    var textfieldSize by remember { mutableStateOf(Size.Zero)}
    val icon = if (expanded)
        Icons.Filled.ArrowDropUp
    else
        Icons.Filled.ArrowDropDown

    //диалоговое окно
    if (openDialog) {
        AlertDialog(
            onDismissRequest = {
                openDialog = false
                text=article.text
                selectedText=tagName
            },
            content = {
                Column(
                    modifier = Modifier
                        .clip(RoundedCornerShape(16.dp))
                        .background(Color.White)
                        .padding(16.dp),
                ) {
                    Text(
                        text = "Edit your article",
                        color = Color(0xff423a99),
                        style = TextStyle(
                            fontSize = 20.sp,
                        ),
                    )
                    Box() {
                        OutlinedTextField(
                            value = selectedText,
                            onValueChange = { selectedText = it },
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(10.dp)
                                .onGloballyPositioned { coordinates ->
                                    textfieldSize = coordinates.size.toSize()
                                },
                            label = {Text("Select Tag")},
                            colors = TextFieldDefaults.textFieldColors(
                                containerColor = Color.White,
                                focusedIndicatorColor = Color(0xff423a99),
                                focusedLabelColor = Color(0xff423a99),
                                unfocusedIndicatorColor = Color(0xff423a99),
                                unfocusedLabelColor = Color(0xff423a99)
                            ),
                            trailingIcon = {
                                Icon(icon,"List of tags",
                                    Modifier.clickable { expanded = !expanded })
                            }
                        )
                        DropdownMenu(
                            expanded = expanded,
                            onDismissRequest = { expanded = false },
                            modifier = Modifier
                                .width(with(LocalDensity.current){textfieldSize.width.toDp()})
                        ) {
                            suggestions.forEach { label ->
                                DropdownMenuItem(
                                    text= {Text(text=label)},
                                    onClick = { selectedText = label
                                        coroutineScope.launch {
                                            tagId= articleItemViewModel.getTagByName(selectedText).id!!
                                        }
                                    }
                                )
                            }
                        }
                    }
                    OutlinedTextField(
                        value = title,
                        onValueChange = {
                            title=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("Article Title") },
                        placeholder = { Text("Write title of article...") },
                        minLines = 3,
                        maxLines = 3,
                    )
                    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("Article Text") },
                        placeholder = { Text("Write text of article...") },
                        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
                                article.text=text
                                article.title=title
                                tagName=selectedText
                                Log.d("Tag",tagId.toString())
                                if(tagId!=null) {
                                    article.tagId = tagId
                                }
                                coroutineScope.launch {
                                    articleItemViewModel.updateArticle(article)
                                }
                            },
                            modifier = Modifier
                                .padding(start=100.dp)
                                .fillMaxWidth(0.5f)
                                .height(40.dp)
                        ) {
                            Text(text = "Edit", fontSize = 20.sp)
                        }
                    }
                }
            },
        )
    }

    Card(
        colors = CardDefaults.outlinedCardColors(
            containerColor = Color.White,
            contentColor = Color(0xff423a99)
        ),
        border = BorderStroke(3.dp, Color(0xffdbdbf1)),
        modifier = modifier
            .clip(shape = RoundedCornerShape(5.dp))
            .clickable{onArticleClick()}
    ) {
        Box(
            modifier = Modifier
                .requiredWidth(width = 393.dp)
                .requiredHeight(height = 199.dp)
        ) {
            Card(
                colors = CardDefaults.outlinedCardColors(
                    containerColor = Color.White
                ),
                border = BorderStroke(3.dp, Color(0xffdbdbf1)),
                content = {},
                modifier = Modifier
                    .requiredWidth(width = 393.dp)
                    .requiredHeight(height = 199.dp)
                    .clip(shape = RoundedCornerShape(5.dp))
                    .background(color = Color.White)
                    .border(border = BorderStroke(3.dp, Color(0xffdbdbf1)),
                        shape = RoundedCornerShape(5.dp)))
            LazyRow(
                modifier = Modifier
                    .requiredWidth(width = 387.dp)
                    .requiredHeight(height = 199.dp)
            ) {
                item {
                    Column(
                        modifier = Modifier
                            .align(alignment = Alignment.TopStart)
                            .offset(x = 15.dp,
                                y = 8.dp)
                            .requiredWidth(width = 351.dp)
                            .requiredHeight(height = 177.dp)
                    ) {
                        LazyColumn(
                            modifier = Modifier
                                .requiredWidth(width = 351.dp)
                                .requiredHeight(height = 150.dp)
                        ) {
                            item {
                                LazyRow(
                                    modifier = Modifier
                                        .requiredWidth(width = 351.dp)
                                        .requiredHeight(height = 20.dp)
                                ) {
                                    item {
                                        Text(
                                            text = "${publishDate}",
                                            color = Color(0xff423a99),
                                            style = TextStyle(
                                                fontSize = 17.sp))
                                    }
                                    item {
                                        Text(
                                            text = "#${tagName}",
                                            color = Color(0xff423a99),
                                            style = TextStyle(
                                                fontSize = 17.sp),
                                            modifier = Modifier
                                                //.align(alignment = Alignment.TopStart)
                                                .offset(x = 12.dp,
                                                    y = 0.dp))
                                    }
                                    item{
                                        if(getUser?.id==article.userId) {
                                            Icon(
                                                modifier=Modifier
                                                    .align(Alignment.End)
                                                    .offset(x = 20.dp,
                                                        y = 0.dp)
                                                    .requiredHeight(30.dp)
                                                    .clickable {
                                                        openDialog=true
                                                    },
                                                imageVector = Icons.Filled.Edit,
                                                contentDescription = "Update Icon",
                                                tint = Color(0xff423a99)
                                            )
                                            Icon(
                                                modifier=Modifier
                                                    .align(Alignment.End)
                                                    .offset(x = 20.dp,
                                                        y = 0.dp)
                                                    .requiredHeight(30.dp)
                                                    .clickable {
                                                        coroutineScope.launch {
                                                            articleItemViewModel.deleteArticle(article)
                                                        }
                                                        navController.navigate(BottomBarScreen.Main.route)
                                                    },
                                                imageVector = Icons.Filled.Close,
                                                contentDescription = "Delete Icon",
                                                tint = Color(0xff423a99)
                                            )
                                        }
                                    }
                                }
                            }
                            item {
                                Text(
                                    text = "${article.title}",
                                    maxLines=4,
                                    color = Color(0xff423a99),
                                    style = TextStyle(
                                        fontSize = 20.sp,
                                        fontWeight = FontWeight.Bold),
                                    modifier = Modifier
                                        //.align(alignment = Alignment.TopStart)
                                        .offset(x = 0.dp,
                                            y = 15.dp)
                                        .requiredWidth(width = 351.dp)
                                        .requiredHeight(height = 100.dp))
                            }
                        }
                        LazyRow(
                            modifier = Modifier
                                //.align(alignment = Alignment.TopStart)
                                .offset(x = 3.dp,
                                    y = 5.dp)
                                .requiredWidth(width = 80.dp)
                                .requiredHeight(height = 25.dp)
                        ) {
                            item {
                                Row(
                                    modifier = Modifier
                                        .requiredWidth(width = 58.dp)
                                        .requiredHeight(height = 22.dp)
                                ) {
                                    Image(
                                        painter = painterResource(id = R.drawable.ic_comment),
                                        contentDescription = "icon \"heart\"",
                                        modifier = Modifier
                                            .requiredWidth(width = 25.dp)
                                            .requiredHeight(height = 22.dp))
                                    Text(
                                        text = "${countComm.value}",
                                        color = Color(0xff423a99),
                                        style = TextStyle(
                                            fontSize = 17.sp),
                                        modifier = Modifier
                                            //.align(alignment = Alignment.TopStart)
                                            .offset(x = 5.dp,
                                                y = 1.dp))
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}


