package com.example.iplace.main.viewModel.mainView

import androidx.compose.foundation.Image
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.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.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
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.navigation.NavHostController
import com.example.iplace.R
import com.example.iplace.main.viewModel.MainViewModel
import com.example.iplace.model.Category
import com.example.iplace.model.Place
import com.example.iplace.model.PlaceInsert
import com.example.iplace.model.Users
import com.example.iplace.ui.theme.brown_contrast
import kotlinx.coroutines.launch
import kotlinx.serialization.Serializable

@Composable
fun AddPlace(navController: NavHostController) {
    val viewModel = MainViewModel()
    val headlinesOswald = FontFamily( //выбор шрифта
        Font(resId = R.font.headlines_oswald)
    )
    val basicNunitosans = FontFamily(
        Font(resId = R.font.basic_nunitosans)
    )

    var user by remember { mutableStateOf<Users?>(null) }
    var idState by remember { mutableStateOf("") }
    var id: Int? by remember { mutableStateOf(null) }
    var title by remember { mutableStateOf("") }
    var img_place by remember { mutableStateOf("") }
    var id_categoryFK by remember { mutableStateOf(1) }
    var description by remember { mutableStateOf("") }
    var address by remember { mutableStateOf("") }
    var mapping by remember { mutableStateOf("") }
    var isAuthor by remember { mutableStateOf(false) }
    var author by remember { mutableStateOf("") }

    var placeList by remember { mutableStateOf<List<Place>>(emptyList()) }

    var categoryList by remember { mutableStateOf<List<Category>>(emptyList()) }



    LaunchedEffect(Unit) { // Запускаем корутину при первом рендере composable
        viewModel.getUserById() // Вызываем функцию из viewModel
        user = viewModel.user.value // Получаем результат из viewModel
        placeList = viewModel.getPlaceList()
        categoryList = viewModel.getCategoryList()
    }
    // Создаем CoroutineScope для запуска корутин
    val coroutineScope = rememberCoroutineScope()

    var expanded by remember { mutableStateOf(false) }


    Image(
        painter = painterResource(id = R.drawable.fon),
        contentDescription = "",
        contentScale = ContentScale.FillHeight,
        modifier = Modifier.fillMaxSize()
    )
    Column(
        modifier = Modifier
            .fillMaxSize()
    ) {
        Spacer(modifier = Modifier.height(20.dp))
        // Верхний блок (2/5 размера экрана)
        Box(
            modifier = Modifier
                .weight(1f)
                .background(Color.LightGray.copy(alpha = 0.8f))
                .padding(16.dp),
            contentAlignment = Alignment.TopCenter
        ) {

            // Кнопки назад и настроек
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                IconButton(onClick = { navController.navigate("MenuV") }) {
                    Icon(Icons.Filled.ArrowBack, contentDescription = "Назад")
                }
            }
            Spacer(modifier = Modifier.height(60.dp))

            // Заголовок "Профиль"
            Text(
                text = "Добавление места",
                fontWeight = FontWeight.Bold,
                modifier = Modifier
                    .padding(top = 32.dp)
                    .fillMaxWidth(),
                textAlign = TextAlign.Center
            )


        }

        // Остальной контент (3/5 размера экрана)
        Box(
            modifier = Modifier
                .weight(3f)
                .fillMaxSize()
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 8.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {

                OutlinedTextField(
                    value = title,
                    onValueChange = { newText -> title = newText },
                    label = { Text("Название", color = Color.Black) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp)
                        .clip(RoundedCornerShape(20.dp)),
                    textStyle = TextStyle(color = Color.Black)
                )
                Spacer(modifier = Modifier.height(10.dp))
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp)
                        .clip(RoundedCornerShape(20.dp))
                        .clickable { expanded = !expanded }
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Button(onClick = { expanded = true },
                            colors = ButtonDefaults.buttonColors(brown_contrast)
                        ) {
                            Text("Выберите категорию")
                        }
                        DropdownMenu(
                            expanded = expanded,
                            onDismissRequest = { expanded = false },
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            categoryList.forEach { category ->
                                DropdownMenuItem(
                                    onClick = {
                                        id_categoryFK = category.id_category
                                        expanded = false
                                    },
                                    text = {
                                        Text(category.title)
                                    }
                                )
                            }
                        }
                    }

                }

                Spacer(modifier = Modifier.height(10.dp))
                OutlinedTextField(
                    value = address,
                    onValueChange = { newText -> address = newText },
                    label = { Text("Адресс", color = Color.Black) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp)
                        .clip(RoundedCornerShape(20.dp)),
                    textStyle = TextStyle(color = Color.Black)
                )
                Spacer(modifier = Modifier.height(10.dp))

                OutlinedTextField(
                    value = description,
                    onValueChange = { newText -> description = newText },
                    label = { Text("Описание", color = Color.Black) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp)
                        .clip(RoundedCornerShape(20.dp)),
                    textStyle = TextStyle(color = Color.Black)
                )
                Spacer(modifier = Modifier.height(10.dp))

                OutlinedTextField(
                    value = mapping,
                    onValueChange = { newText ->
                        mapping = newText
                    },
                    label = { Text("Координаты", color = Color.Black) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp)
                        .clip(RoundedCornerShape(20.dp)),
                    textStyle = TextStyle(color = Color.Black)
                )

                Spacer(modifier = Modifier.height(15.dp))

                OutlinedTextField(
                    value = "",
                    onValueChange = { /* Не используется */ },
                    label = { Text("Быть автором?") },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp)
                        .clip(RoundedCornerShape(20.dp)),
                    trailingIcon = {
                        Checkbox(
                            checked = isAuthor,
                            onCheckedChange = { isAuthor = it }
                        )
                    }
                )

                LaunchedEffect(isAuthor) {
                    author = if (isAuthor) user?.name.toString() else ""
                }
                Spacer(modifier = Modifier.height(10.dp))
                Text(
                    text = viewModel.InfoText.value,
                    fontSize = 18.sp,
                    color = Color.DarkGray
                )
                Spacer(modifier = Modifier.height(20.dp))
                Button(

                    onClick = {
                        val newPlace =
                            PlaceInsert(
                                title = title,
                                img_place = img_place,
                                id_categoryFK = id_categoryFK,
                                description = description,
                                address = address,
                                mapping = mapping,
                                author = author
                            )
                        user?.let {
                            coroutineScope.launch {
                                newPlace?.let { it1 -> viewModel.insertPlace(it1, navController) }
                            }
                        }
                    },
//
                    modifier = Modifier.width(290.dp).height(50.dp),
                    colors = ButtonDefaults.buttonColors(brown_contrast)
                ) {
                    Text(
                        text = "Сохранить",
                        fontSize = 24.sp,
                        fontFamily = basicNunitosans
                    )
                }


            }
        }
    }
}