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

import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
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.material3.Button
import androidx.compose.material3.ButtonDefaults
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.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
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.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.ui.theme.beige_white
import com.example.iplace.ui.theme.brown_contrast
import java.io.IOException
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.ui.text.TextStyle


@Composable
fun CreatingUser(navController: NavHostController) {
    val viewModel = MainViewModel()
    val headlinesOswald = FontFamily( //загрузка шрифта
        Font(resId = R.font.headlines_oswald)
    )
    val basicNunitosans = FontFamily(
        Font(resId = R.font.basic_nunitosans)
    )



    var selectedImageUri by remember { mutableStateOf<Uri?>(null) }
    var imageBitmap by remember { mutableStateOf<androidx.compose.ui.graphics.ImageBitmap?>(null) }

    val context = LocalContext.current
    val launcher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        selectedImageUri = uri
        if (uri != null) {
            try {
                val bitmap = uri.toBitmap(context)
                imageBitmap = bitmap.asImageBitmap()
            } catch (e: IOException) {
                // Обработка ошибок
            }
        }
    }

    var nameUser by remember { mutableStateOf("") }
    var address by remember { mutableStateOf("") }
    var about_me by remember { mutableStateOf("") }
    var expanded by remember { mutableStateOf(false) }
    var selectedItem by remember { mutableStateOf("") }
    val id_genderFK = remember { mutableStateOf("") }

    val genderOptions = listOf(
        Pair("Мужчина", "1"),
        Pair("Женщина", "2")
    )


    Image(
        painter = painterResource(id = R.drawable.cu6),
        contentDescription = "",
        contentScale = ContentScale.FillHeight,
        modifier = Modifier.fillMaxSize()
    )

    Column(
        modifier = Modifier
            .fillMaxSize(),
        verticalArrangement = Arrangement.Top,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Spacer(modifier = Modifier.height(60.dp)) //отступ между блоками
        Text(
            text = "I.PLACE",
            fontSize = 45.sp,
            fontWeight = FontWeight.Bold,
            fontFamily = headlinesOswald
        )
        Spacer(modifier = Modifier.height(55.dp))
        Box(
            modifier = Modifier
                .width(350.dp)
                .height(700.dp)
                .clip(RoundedCornerShape(40.dp))
                .background(beige_white.copy(alpha = 0.8f))
//        .alpha(0.8f) //возможная прозрачность формы
        ) {
            Column(
                modifier = Modifier.fillMaxSize(),
                verticalArrangement = Arrangement.Top,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Spacer(modifier = Modifier.height(5.dp)) // Отступ от заголовка

                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    IconButton(onClick = { navController.navigate("registration") }) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack, // Или другой иконки
                            contentDescription = "Назад",
                            modifier = Modifier.padding(top = 20.dp)
                        )
                    }
                    Spacer(modifier = Modifier.width(35.dp)) // Отступ между кнопкой и текстом
                    Text(
                        text = "Создание пользователя",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        fontFamily = headlinesOswald,
                        modifier = Modifier.padding(top = 20.dp) // Отступ сверху
                    )
                }

                Spacer(modifier = Modifier.height(40.dp)) // Отступ от заголовка

                OutlinedTextField(
                    value = nameUser,
                    onValueChange = { newText -> nameUser = 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))

                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    OutlinedTextField(
                        value = selectedItem,
                        onValueChange = { selectedItem = it },
                        readOnly = true,
                        label = { Text("Пол", color = Color.Black) },
                        trailingIcon = {
                            IconButton(onClick = { expanded = !expanded }) {
                                Icon(Icons.Filled.ArrowDropDown, contentDescription = null)
                            }
                        },
                        modifier = Modifier.fillMaxWidth(),
                        textStyle = TextStyle(color = Color.Black)
                    )

                    DropdownMenu(
                        expanded = expanded,
                        onDismissRequest = { expanded = false },
                        modifier = Modifier
                            .fillMaxWidth()
                            .width(200.dp)
                    ) {
                        genderOptions.forEach { (gender, id) ->
                            DropdownMenuItem(
                                onClick = {
                                    selectedItem = gender
                                    id_genderFK.value = id
                                    expanded = false
                                },
                                text = {
                                    Text(text = gender)
                                }
                            )
                        }
                    }
                }



                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 = about_me,
                    onValueChange = { newText -> about_me = 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))
                Text(
                    text = viewModel.InfoText.value,
                    fontSize = 18.sp,
                    color = Color.DarkGray
                )
                Spacer(modifier = Modifier.height(20.dp))

                Button(
                    onClick = {
                        viewModel.AddUserFun(nameUser,  address , about_me,  "1",  "dsad", navController)

                              },
                    modifier = Modifier.width(290.dp).height(50.dp),
                    colors = ButtonDefaults.buttonColors(brown_contrast)
                ) {
                    Text(
                        text = "Создать",
                        fontSize = 24.sp,
                        fontFamily = basicNunitosans
                    )
                }

                Spacer(modifier = Modifier.height(16.dp)) // Отступ снизу
            }
        }
    }
}

fun Uri.toBitmap(context: android.content.Context): android.graphics.Bitmap {
    val resolver = context.contentResolver
    return android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(this))
}
