package com.example.tomatoandpotatoapp.Screens

import android.widget.ImageButton
import android.widget.Toast
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.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
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.CircularProgressIndicator
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.material3.TextFieldColors
import androidx.compose.material3.TextFieldDefaults
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.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.unit.toSize
import com.example.tomatoandpotatoapp.ViewModelsPack.SupabaseAuthViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.tomatoandpotatoapp.R
import com.example.tomatoandpotatoapp.data.models.UserState
import com.example.tomatoandpotatoapp.navigationPack.Screens
import com.example.tomatoandpotatoapp.utils.EditProfileString


//@Preview
@Composable
fun MyProfile(
    viewModel: SupabaseAuthViewModel = viewModel(),
    navController: NavController
) {
    val userState by viewModel.userState
    val people by viewModel.user
    val f = remember { mutableStateOf(false) }
    val context = LocalContext.current
    val f2 = remember { mutableStateOf(true) }
    val out = remember { mutableStateOf(false) }
    var mSelectedText by remember { mutableStateOf("") }
    var expanded by remember { mutableStateOf(false) }
    var mTextFieldSize by remember { mutableStateOf(Size.Zero) }

    val genders = viewModel.genders

    val icon = if (expanded)
        Icons.Filled.KeyboardArrowUp
    else
        Icons.Filled.KeyboardArrowDown

    if (f2.value) {
        viewModel.selectPeople()
        f2.value = false
    }

    if (people.isNotEmpty()) {
        val firstName = remember {
            mutableStateOf(people.last().firstName)
        }
        val genderId = remember {
            mutableStateOf(people.last().genderId)
        }
        val birthDate = remember {
            mutableStateOf(people.last().birthDate)
        }

        Box(modifier = Modifier.fillMaxSize()) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(
                        brush = Brush.verticalGradient(
                            colors = listOf(
                                Color(0xFF666666).copy(alpha = 0.85f),
                                Color(0xFF666666).copy(alpha = 0.1f)
                            ),
                            startY = 0.0f,
                            endY = 1500.0f
                        )
                    )
            )
            Column(modifier = Modifier.fillMaxSize()) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(95.dp)
                        .background(color = Color(0xffD9D9D9)),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "Профиль",
                        fontWeight = FontWeight.W800,
                        color = Color.Black,
                        fontSize = 25.sp
                    )
                }

                Spacer(modifier = Modifier.height(60.dp))
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center
                ) {

                    EditProfileString(search = firstName.value,
                        onValueChange = {firstName.value = it}, enabled = true)
                }

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

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center
                ) {

                    EditProfileString(search = birthDate.value,
                        onValueChange = {birthDate.value = it}, enabled = true)
                }

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

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center
                ) {

                    OutlinedTextField(
                        value = mSelectedText,
                        onValueChange = {  },
                        modifier = Modifier
                            .height(50.dp)
                            .width(316.dp)
                            .onGloballyPositioned { coordinates ->
                                mTextFieldSize = coordinates.size.toSize()
                            },
                        shape = RoundedCornerShape(20),
                        colors = TextFieldDefaults.colors(
                            focusedContainerColor = Color(0xFFF2D6FA),
                            focusedIndicatorColor = Color(0xFF4C2259),
                            focusedTextColor = Color.Black,
                            disabledIndicatorColor = Color.Transparent,
                            unfocusedIndicatorColor = Color.Transparent,
                            cursorColor = Color.Black,
                            focusedSupportingTextColor = Color.Black
                        ),
                        label = {
                            Text(
                                "Пол",
                                fontWeight = FontWeight.W600,
                                color = Color.Black
                            )
                        },
                        trailingIcon = {
                            Icon(icon, "contentDescription",
                                Modifier.clickable { expanded = !expanded })
                        }
                    )
                    DropdownMenu(
                        expanded = expanded,
                        onDismissRequest = { expanded = false },
                        modifier = Modifier
                            .width(with(LocalDensity.current) { mTextFieldSize.width.toDp() })
                    ) {
                        genders.value.forEach { label ->
                            DropdownMenuItem(text = {
                                Text(
                                    text = label.genderTitle,
                                    fontSize = 15.sp, fontWeight = FontWeight.Normal
                                )
                            },
                                onClick = {
                                    mSelectedText = label.genderTitle
                                    genderId.value = label.id
                                    expanded = false
                                }
                            )
                        }
                    }
                }

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

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center
                ) {
                    Button(
                        onClick = {},
                        modifier = Modifier
                            .height(50.dp)
                            .width(316.dp),
                        shape = RoundedCornerShape(20),
                        colors = ButtonDefaults
                            .buttonColors(containerColor = Color(0xFFF5F5F9))
                    ) {
                        Text(
                            text = "Мои растения",
                            fontWeight = FontWeight.W800,
                            color = Color.Black,
                            fontSize = 22.sp
                        )

                    }
                }

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

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Button(
                        onClick = { },
                        modifier = Modifier
                            .width(278.dp)
                            .height(45.dp),
                        shape = RoundedCornerShape(20),
                        colors = ButtonDefaults
                            .buttonColors(containerColor = Color(0xff78EE99))
                    )
                    {
                        Text(
                            text = "Сохранить",
                            fontSize = 22.sp,
                            fontWeight = FontWeight.W700,
                            color = Color.White
                        )
                    }
                }

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

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Button(
                        onClick = {viewModel.singOut(context) },
                        modifier = Modifier
                            .width(278.dp)
                            .height(45.dp),
                        shape = RoundedCornerShape(20),
                        colors = ButtonDefaults
                            .buttonColors(containerColor = Color(0xffFC5050))
                    )
                    {
                        Text(
                            text = "Выход",
                            fontSize = 22.sp,
                            fontWeight = FontWeight.W700,
                            color = Color.White
                        )
                    }
                }

                Spacer(modifier = Modifier.weight(0.2f))

                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(95.dp)
                        .background(color = Color(0xff718588)),
                    horizontalArrangement = Arrangement.SpaceEvenly
                ) {
                    IconButton(
                        onClick = { },
                        modifier = Modifier.size(120.dp)
                    ) {
                        Icon(
                            bitmap = ImageBitmap.imageResource(R.drawable.message),
                            contentDescription = "Поддержка",
                            modifier = Modifier.size(55.dp)
                        )
                    }
                    IconButton(
                        onClick = { navController.navigate(Screens.PlantsCatalogScreen.route) },
                        modifier = Modifier.size(120.dp)
                    ) {
                        Icon(
                            bitmap = ImageBitmap.imageResource(R.drawable.catalog),
                            contentDescription = "Каталог",
                            modifier = Modifier.size(55.dp)
                        )
                    }
                    IconButton(
                        onClick = { navController.navigate(Screens.ProfileScreen.route) },
                        modifier = Modifier.size(120.dp)
                    ) {
                        Icon(
                            bitmap = ImageBitmap.imageResource(R.drawable.profileblack),
                            contentDescription = "Профиль",
                            modifier = Modifier.size(55.dp)
                        )
                    }

                }
            }
        }
    }
    if (f.value) {
        when (userState) {
            is UserState.Loading -> {
                CircularProgressIndicator()
            }

            is UserState.Success -> {
                val message = (userState as UserState.Success).message
                Toast.makeText(context, "Данные успещно сохранены!", Toast.LENGTH_SHORT).show()
                f.value = false
            }

            is UserState.Error -> {
                val message = (userState as UserState.Error).message
                f.value = false
            }
        }
    }

    if (out.value) {
        when (userState) {
            is UserState.Loading -> {
                CircularProgressIndicator()
            }

            is UserState.Success -> {
                navController.navigate(Screens.ChoiceScreen.route)
                out.value = false
            }

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