package com.example.dtf.screens

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
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 com.example.dtf.PreferencesManager
import com.example.dtf.models.Category
import com.example.dtf.utils.ScreenPaths
import com.example.dtf.viewmodels.NewPostViewModel
import com.example.dtf.widgets.MyTextField

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

    val selectedCategory = remember { mutableStateOf(Category(null, "")) }
    val expanded = remember { mutableStateOf(false) }

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

    val viewModel = hiltViewModel<NewPostViewModel>()
    val success = viewModel.addingPostState.observeAsState().value
    val categories = viewModel.getCategories().collectAsState(initial = listOf())

    if (success == true) {
        navController.navigate(ScreenPaths.Posts.route) {
            popUpTo(ScreenPaths.Posts.route) {
                inclusive = true
            }
        }
    }

    if (success == false) {
        AlertDialog(
            title = {
                Text(
                    text = "Ошибка",
                    fontWeight = FontWeight.Bold,
                    fontSize = 20.sp
                )
            },
            text = {
                Text(
                    text = "Нельзя создать новость с пустым заголовком или содержанием",
                    fontWeight = FontWeight.Normal,
                    fontSize = 16.sp
                )
            },
            onDismissRequest = {
                viewModel.calmAddingState()
            },
            buttons = {
                TextButton(
                    onClick = {
                        viewModel.calmAddingState()
                    }
                ) {
                    Text("ОК")
                }
            }
        )
    }

    Column(
        modifier = Modifier.verticalScroll(rememberScrollState()),
        verticalArrangement = Arrangement.spacedBy(10.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Button(
            {
                expanded.value = true
            },
            colors = ButtonDefaults.buttonColors(Color(0xFFFFFFFF)),
            border = BorderStroke(1.dp, Color(0xFF0085FF)),
            shape = RoundedCornerShape(15.dp),
            modifier = Modifier
                .fillMaxWidth()
                .padding(15.dp, 10.dp, 15.dp, 0.dp)
        ) {
            Text(
                text = selectedCategory.value.name,
                style = TextStyle(
                    fontSize = 24.sp,
                    fontWeight = FontWeight(400),
                    color = Color(0xFF000000),
                )
            )
            DropdownMenu(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 15.dp),
                expanded = expanded.value,
                onDismissRequest = {expanded.value = false}
            ) {
                categories.value.forEach { category ->
                    DropdownMenuItem(
                        onClick = {
                            selectedCategory.value = category
                            expanded.value = false
                        },
                    ) {
                        Text(
                            text = category.name,
                            fontSize = 16.sp,
                            textAlign = TextAlign.Center
                        )
                    }
                }
            }
        }
        MyTextField(
            value = title,
            "Заголовок",
            onChanged = {title.value = it},
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 15.dp),
            backgroundColor = Color(0xFFFEFEFE)
        )
        MyTextField(
            value = content,
            "Содержимое",
            onChanged = {content.value = it},
            modifier = Modifier
                .fillMaxWidth()
                .heightIn(min = 400.dp)
                .padding(horizontal = 15.dp),
            backgroundColor = Color(0xFFFEFEFE),
            false
        )

        Button(
            {
                if (selectedCategory.value.id != null) {
                    viewModel.addPost(sharedPref, selectedCategory.value.id!!, title.value.text, content.value.text)
                }
            },
            colors = ButtonDefaults.buttonColors(Color(0xFF388DF2)),
            border = BorderStroke(1.dp, Color(0xFF0085FF)),
            shape = RoundedCornerShape(15.dp),
            modifier = Modifier.fillMaxWidth(0.5f)
        ) {
            Text(
                text = "Опубликовать",
                style = TextStyle(
                    fontSize = 24.sp,
                    fontWeight = FontWeight(400),
                    color = Color(0xFFFFFFFF),
                )
            )
        }
        Spacer(modifier = Modifier.height(70.dp))
    }
}