import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.offset
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.DateRange
import androidx.compose.material.icons.filled.Face
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.Person
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
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.derivedStateOf
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.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
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.compose.ui.unit.toSize
import androidx.navigation.NavController
import com.example.tasks.model.UserState
import com.example.tasks.navigation.Screen
import com.example.tasks.screens.LoadingComponent
import com.example.tasks.viewModels.AuthViewModel
import com.example.tasks.viewModels.DatabaseViewModel
import com.vanpra.composematerialdialogs.MaterialDialog
import com.vanpra.composematerialdialogs.datetime.date.datepicker
import com.vanpra.composematerialdialogs.rememberMaterialDialogState
import java.io.ByteArrayOutputStream
import java.time.LocalDate
import java.time.format.DateTimeFormatter

@RequiresApi(Build.VERSION_CODES.O)
@Composable
fun CreateProfile(
    navController: NavController,
    viewModel: AuthViewModel,
    viewModelDatabase: DatabaseViewModel
) {
    val context = LocalContext.current
    val enabled = remember { mutableStateOf(false) }
    val dateDialogState = rememberMaterialDialogState()
    val userState by viewModel.userState
    val flag = remember { mutableStateOf(false) }
    val surnameFlag = remember { mutableStateOf(false) }
    val nameFlag = remember { mutableStateOf(false) }
    val dateOfBirthFlag = remember { mutableStateOf(false) }
    val genderFlag = remember { mutableStateOf(false) }
    var pickedDate by remember { mutableStateOf(LocalDate.now()) }
    val name = remember { mutableStateOf("") }
    val surname = remember { mutableStateOf("") }
    val patronymic = remember { mutableStateOf("") }
    val avatar = remember { mutableStateOf(byteArrayOf()) }
    val focusManager = LocalFocusManager.current
    val urii = remember { mutableStateOf("") }
    val keyboardController = LocalSoftwareKeyboardController.current
    val launcher =
        rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri == null) return@rememberLauncherForActivityResult
            avatar.value = bitmapToByteArray(context, uri)
            urii.value = uri.schemeSpecificPart

        }
    var expanded by remember {
        mutableStateOf(false)
    }
    var currentUserState by remember { mutableStateOf("") }
    val list = listOf("Мужской", "Женский")
    var selectedItem by remember {
        mutableStateOf("")
    }
    var textFiledSize by remember {
        mutableStateOf(Size.Zero)
    }
    val icon = if (expanded) {
        Icons.Filled.KeyboardArrowUp
    } else {
        Icons.Filled.KeyboardArrowDown
    }

    val formattedDate by remember {
        derivedStateOf { DateTimeFormatter.ofPattern("dd.MM.yyyy").format(pickedDate) }
    }
    val formattedDateFromBase by remember {
        derivedStateOf { DateTimeFormatter.ofPattern("yyyy-MM-dd").format(pickedDate) }
    }

    Spacer(modifier = Modifier.height(20.dp))
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0xFF951DDD))
            .pointerInput(Unit) {
                detectTapGestures(onTap = {
                    keyboardController?.hide()
                    focusManager.clearFocus()
                })
            }
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(30.dp)
                .padding(top = 40.dp),
            horizontalAlignment = Alignment.Start,
            verticalArrangement = Arrangement.Center
        ) {

            Text(
                "Создание профиля",
                fontWeight = FontWeight.Bold,
                fontSize = 27.sp,
                color = Color.White,
                modifier = Modifier.padding(bottom = 10.dp)
            )
            Spacer(modifier = Modifier.height(20.dp))
            Button(
                onClick = { launcher.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) },
                modifier = Modifier
                    .height(height = 50.dp)
                    .width(width = 320.dp)
                    .padding(bottom = 10.dp),
                colors = ButtonColors(
                    contentColor = Color(0xFF951DDD),
                    containerColor = Color.White,
                    disabledContentColor = Color(0xFF951DDD),
                    disabledContainerColor = Color.White
                ),
                shape = RoundedCornerShape(5.dp)
            ) {
               if(avatar.value.isEmpty()){
                   Text("Добавить аватарку")
               }
                else{
                   Text(urii.value)
               }
            }
            Column {
                OutlinedTextField(value = surname.value,
                    onValueChange = { surname.value = it },
                    shape = RoundedCornerShape(5.dp),
                    modifier = Modifier
                        .height(height = 56.dp)
                        .width(width = 320.dp),
                    leadingIcon = { Icon(Icons.Filled.Person, contentDescription = "Фамилия") },
                    colors = TextFieldDefaults.colors(
                        focusedContainerColor = Color(0XFFF5F5F9),
                        focusedIndicatorColor = Color(0xFFEBEBEB),
                        focusedTextColor = Color.Black,
                        disabledIndicatorColor = Color.Transparent,
                        unfocusedIndicatorColor = Color.Transparent,
                        cursorColor = Color(0XFF578FFF),
                        focusedSupportingTextColor = Color(0xFF00000)
                    ),

                    isError = surnameFlag.value,
                    placeholder = {
                        Text(
                            modifier = Modifier.fillMaxWidth(),
                            text = "Фамилия",
                            fontWeight = FontWeight.Normal,
                            fontSize = 15.sp,
                            color = Color(0XFF939396)
                        )
                    }
                )

                if (surname.value.isEmpty()) {
                    surnameFlag.value = true
                    Text("Введите фамилию", color = Color(0xFFFEB3F6), fontSize = 10.sp)
                } else {
                    surnameFlag.value = false
                }

            }
            Spacer(modifier = Modifier.height(20.dp))
            Column {
                OutlinedTextField(value = name.value, onValueChange = { it -> name.value = it },
                    leadingIcon = { Icon(Icons.Filled.Person, contentDescription = "Имя") },
                    colors = TextFieldDefaults.colors(
                        focusedContainerColor = Color(0XFFF5F5F9),
                        focusedIndicatorColor = Color(0xFFEBEBEB),
                        focusedTextColor = Color.Black,
                        disabledIndicatorColor = Color.Transparent,
                        unfocusedIndicatorColor = Color.Transparent,
                        cursorColor = Color(0XFF578FFF),
                        focusedSupportingTextColor = Color(0xFF00000)
                    ),
                    modifier = Modifier
                        .height(height = 56.dp)
                        .width(width = 320.dp),
                    isError = nameFlag.value,

                    placeholder = {
                        Text(
                            modifier = Modifier.fillMaxWidth(),
                            text = "Имя",
                            fontWeight = FontWeight.Normal,
                            fontSize = 15.sp,
                            color = Color(0XFF939396)
                        )
                    }
                )

                if (name.value.isEmpty()) {
                    nameFlag.value = true
                    Text("Введите имя", color = Color(0xFFFEB3F6), fontSize = 10.sp)
                } else {
                    nameFlag.value = false
                }

            }
            Spacer(modifier = Modifier.height(20.dp))
            Column {
                OutlinedTextField(value = patronymic.value,
                    onValueChange = { it -> patronymic.value = it },
                    leadingIcon = { Icon(Icons.Filled.Person, contentDescription = "Отчечство") },
                    colors = TextFieldDefaults.colors(
                        focusedContainerColor = Color(0XFFF5F5F9),
                        focusedIndicatorColor = Color(0xFFEBEBEB),
                        focusedTextColor = Color.Black,
                        disabledIndicatorColor = Color.Transparent,
                        unfocusedIndicatorColor = Color.Transparent,
                        cursorColor = Color(0XFF578FFF),
                        focusedSupportingTextColor = Color(0xFF00000)
                    ),
                    modifier = Modifier
                        .height(height = 56.dp)
                        .width(width = 320.dp),
                    placeholder = {
                        Text(
                            modifier = Modifier.fillMaxWidth(),
                            text = "Отчетсво",
                            fontWeight = FontWeight.Normal,
                            fontSize = 15.sp,
                            color = Color(0XFF939396)
                        )
                    }
                )


            }

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

            val padding = 10.dp
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .align(Alignment.Start)
                    .clip(RoundedCornerShape(10.dp))

            ) {
                Button(
                    onClick = { dateDialogState.show() }, modifier = Modifier
                        .fillMaxWidth(1f)
                        .height(height = 56.dp)
                        .width(width = 320.dp),
                    shape = RoundedCornerShape(size = 10.dp),
                    border = if (dateOfBirthFlag.value) {
                        BorderStroke(1.dp, Color(0xFFFEB3F6))
                    } else {
                        BorderStroke(0.dp, Color.Transparent)
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(0XFFF5F5F9),
                        contentColor = Color(0XFF40484d)
                    )
                ) {
                    Icon(
                        Icons.Filled.DateRange,
                        contentDescription = "Дата рождения",
                        modifier = Modifier
                            .offset(x = -padding)
                            .padding(end = 2.dp)
                    )
                    if (pickedDate == LocalDate.now()) {
                        Text(
                            "Дата рождения",
                            fontSize = 15.sp,
                            fontWeight = FontWeight.Normal,
                            color = Color(0XFF939396),
                            modifier = Modifier.fillMaxWidth(),
                            textAlign = TextAlign.Start
                        )
                    } else {
                        Text(
                            formattedDate.toString(),
                            fontSize = 15.sp,
                            fontWeight = FontWeight.Normal,
                            color = Color.Black,
                            modifier = Modifier.fillMaxWidth(),
                            textAlign = TextAlign.Start
                        )
                    }

                }
                if (pickedDate == LocalDate.now()) {
                    dateOfBirthFlag.value = true
                    Text("Введите дату рождения", color = Color(0xFFFEB3F6), fontSize = 10.sp)
                } else {
                    dateOfBirthFlag.value = false
                }

            }
            Spacer(modifier = Modifier.height(20.dp))

            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .clip(RoundedCornerShape(10.dp))

            ) {

                OutlinedTextField(value = selectedItem,
                    onValueChange = {
                        selectedItem = it
                    },
                    leadingIcon = {
                        Icon(
                            Icons.Filled.Face,
                            contentDescription = "Пол"
                        )
                    },
                    enabled = false,
                    colors = TextFieldDefaults.colors(
                        focusedContainerColor = Color(0XFFF5F5F9),
                        focusedIndicatorColor = Color(0xFFEBEBEB),
                        focusedTextColor = Color(0XFF578FFF),
                        disabledIndicatorColor = Color.Transparent,
                        unfocusedIndicatorColor = Color.Transparent,
                        cursorColor = Color(0XFF578FFF),
                        focusedSupportingTextColor = Color(0xFF00000)
                    ),
                    modifier = Modifier
                        .fillMaxWidth(1f)
                        .background(Color(0XFFF5F5F9))
                        .height(height = 56.dp)
                        .width(width = 320.dp)
                        .clickable { expanded = !expanded }
                        .onGloballyPositioned { coordinates ->
                            textFiledSize = coordinates.size.toSize()
                        },
                    isError = genderFlag.value,
                    trailingIcon = {
                        Icon(
                            icon,
                            contentDescription = ""
                        )
                    },
                    placeholder = {
                        Text(
                            modifier = Modifier.fillMaxWidth(),
                            text = "Пол",
                            fontWeight = FontWeight.Normal,
                            fontSize = 15.sp,
                            color = Color(0XFF939396)
                        )
                    }
                )


                DropdownMenu(
                    expanded = expanded,
                    onDismissRequest = { expanded = false },
                    modifier = Modifier
                        .width(with(LocalDensity.current) { textFiledSize.width.toDp() })
                        .background(Color(0XFFF5F5F9))
                ) {
                    list.forEach { label ->
                        DropdownMenuItem(text = {
                            Text(
                                text = label,
                                fontSize = 15.sp,
                                fontWeight = FontWeight.Normal
                            )
                        }, onClick = {
                            selectedItem = label
                            expanded = false

                        })
                    }


                }

                if (selectedItem == "") {
                    genderFlag.value = true
                    Text("Выберете пол", color = Color(0xFFFEB3F6), fontSize = 10.sp)
                } else {
                    genderFlag.value = false
                }
            }
            Spacer(modifier = Modifier.height(30.dp))
            Box(
                modifier = Modifier
                    .clip(RoundedCornerShape(10.dp))

            ) {
                Button(
                    modifier = Modifier
                        .width(width = 500.dp)
                        .height(height = 56.dp),
                    onClick = {
                        viewModel.addAvatar(avatar.value)
                        viewModel.addUser(
                            name = name.value,
                            surname = surname.value,
                            patronymic = patronymic.value,
                            date_of_birth = formattedDateFromBase,
                            gender = selectedItem
                        )

                        flag.value = true

                    },
                    shape = RoundedCornerShape(size = 10.dp),
                    enabled = enabled.value,
                    colors = ButtonColors(
                        contentColor = Color(0xFF951DDD),
                        containerColor = Color.White,
                        disabledContentColor = Color.LightGray,
                        disabledContainerColor = Color.White
                    )
                ) {
                    Text(
                        text = "Создать",
                        fontSize = 20.sp,
                        fontWeight = FontWeight.W900,
                    )
                }
            }

        }
        if (!surnameFlag.value && !nameFlag.value && !dateOfBirthFlag.value && !genderFlag.value) {
            enabled.value = true
        }
        else{
            enabled.value = false
        }

        if (flag.value) {
            when (userState) {
                is UserState.Loading -> {
                    LoadingComponent()
                }

                is UserState.Success -> {
                    val message = (userState as UserState.Success).message
                    currentUserState = message

                    navController.navigate(Screen.AppNavigationCustomers.route)
                    viewModelDatabase.profileData()
                    flag.value = false
                }

                is UserState.Error -> {
                    val message = (userState as UserState.Error).message
                    currentUserState = message
                    Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
                    flag.value = false
                }
            }

            if (currentUserState.isNotEmpty()) {
                println(currentUserState)
            }
        }
    }

    MaterialDialog(
        dialogState = dateDialogState,
        buttons = {
            positiveButton(text = "Ok")
            negativeButton("cancel")
        })
    {
        datepicker(
            initialDate = LocalDate.now(),
            allowedDateValidator = {
                it.year <= LocalDate.now().year
            }


        ) {
            pickedDate = it

        }
    }
}


fun bitmapToByteArray(context: Context, uri: Uri): ByteArray {
    val inputStream = context.contentResolver.openInputStream(uri)
    val bitmap = BitmapFactory.decodeStream(inputStream)
    val baos = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos)
    return baos.toByteArray()
}








