package com.example.tomatoandpotatoapp.Screens

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
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.PaddingValues
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.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.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.draw.clip
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.graphics.asImageBitmap
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
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.res.imageResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
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 coil.compose.AsyncImagePainter
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import com.example.tomatoandpotatoapp.R
import com.example.tomatoandpotatoapp.data.models.UserState
import com.example.tomatoandpotatoapp.navigationPack.Screens
import com.example.tomatoandpotatoapp.utils.EditProfileString
import java.io.ByteArrayOutputStream


@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 keyboardController = LocalSoftwareKeyboardController.current
    val focusManager = LocalFocusManager.current
    val genders = viewModel.genders

    val save = remember { mutableStateOf(false) }

    val addAvatar = remember { mutableStateOf(false) }

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

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

    if (people.isNotEmpty()) {

        val newAvatar = remember { mutableStateOf(byteArrayOf()) }

        val avatarFrombase = rememberAsyncImagePainter(
            model = ImageRequest.Builder(LocalContext.current).data(people.last().image)
                .size(100, 100).build()
        ).state

        val launcher =
            rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
                if (uri == null) return@rememberLauncherForActivityResult
                newAvatar.value = bitmapToByteArray(context, uri)

            }


        val newAvatarBitmap = remember { mutableStateOf<ImageBitmap?>(null) }

        val firstName = remember {
            mutableStateOf(people.last().firstName)
        }
        val genderId = remember {
            mutableStateOf(
                if (people.last().genderId == null) {
                    0
                } else {
                    people.last().genderId
                }
            )
        }
        val birthDate = remember {
            mutableStateOf(
                if (people.last().birthDate.isNullOrEmpty()) {
                    ""
                } else {
                    people.last().birthDate
                }
            )
        }

        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(color = Color.White)
        ) {
            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()
                    .pointerInput(Unit) {
                        detectTapGestures(onTap = {
                            keyboardController?.hide()
                            focusManager.clearFocus()
                        })
                    },
            ) {
                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) {
                    if (newAvatar.value.isEmpty()) {
                        if (avatarFrombase is AsyncImagePainter.State.Success) {
                            Box(
                                modifier = Modifier
                                    .width(100.dp)
                                    .height(100.dp)
                                    .clip(RoundedCornerShape(50.dp))
                            ) {
                                Button(
                                    onClick = {
                                        launcher.launch(
                                            PickVisualMediaRequest(
                                                ActivityResultContracts.PickVisualMedia.ImageOnly
                                            )
                                        )
                                    },
                                    colors = ButtonDefaults.buttonColors(
                                        containerColor = Color.White,
                                        disabledContainerColor = Color.White
                                    ), modifier = Modifier
                                        .width(100.dp)
                                        .height(100.dp),
                                    contentPadding = PaddingValues(0.dp)
                                ) {
                                    Image(
                                        modifier = Modifier
                                            .height(100.dp)
                                            .width(100.dp),
                                        painter = avatarFrombase.painter,
                                        contentDescription = "",
                                        contentScale = ContentScale.Crop
                                    )
                                }
                            }
                        }
                        if (avatarFrombase is AsyncImagePainter.State.Loading) {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(200.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                CircularProgressIndicator()
                            }
                        }
                        if (avatarFrombase is AsyncImagePainter.State.Error) {
                            Box(
                                modifier = Modifier
                                    .width(100.dp)
                                    .height(100.dp)
                                    .clip(RoundedCornerShape(50.dp))
                            ) {
                                Button(
                                    onClick = {
                                        launcher.launch(
                                            PickVisualMediaRequest(
                                                ActivityResultContracts.PickVisualMedia.ImageOnly
                                            )
                                        )
                                    },
                                    colors = ButtonDefaults.buttonColors(
                                        containerColor = Color.White,
                                        disabledContainerColor = Color.White
                                    ), modifier = Modifier
                                        .width(100.dp)
                                        .height(100.dp),
                                    contentPadding = PaddingValues(0.dp)
                                ) {
                                    Image(
                                        modifier = Modifier
                                            .height(100.dp)
                                            .width(100.dp),
                                        painter = painterResource(R.drawable.plugavatar),
                                        contentDescription = "",
                                        contentScale = ContentScale.Crop
                                    )
                                }
                            }
                        }
                    } else {
                        newAvatarBitmap.value = ByteArrayImage(newAvatar.value)
                        Box(
                            modifier = Modifier
                                .width(100.dp)
                                .height(100.dp)
                                .clip(RoundedCornerShape(50.dp))
                        ) {
                            Button(
                                onClick = {
                                    save.value = true
                                    launcher.launch(
                                        PickVisualMediaRequest(
                                            ActivityResultContracts.PickVisualMedia.ImageOnly
                                        )
                                    )
                                },
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = Color.White,
                                    disabledContainerColor = Color.White
                                ), modifier = Modifier
                                    .width(100.dp)
                                    .height(100.dp),
                                contentPadding = PaddingValues(0.dp)
                            ) {
                                Image(
                                    modifier = Modifier
                                        .height(100.dp)
                                        .width(100.dp),
                                    bitmap = newAvatarBitmap.value!!,
                                    contentDescription = "",
                                    contentScale = ContentScale.Crop
                                )
                            }
                        }

                    }
                }

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

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

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

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

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

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

                Column(
                    modifier = Modifier.fillMaxWidth(),
                    verticalArrangement = Arrangement.Center,
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {

                    OutlinedTextField(
                        value = mSelectedText,
                        onValueChange = { },

                        modifier = Modifier
                            .height(50.dp)
                            .width(316.dp)
                            .onGloballyPositioned { coordinates ->
                                mTextFieldSize = coordinates.size.toSize()
                            }
                            .clickable {
                                expanded = !expanded
                            },
                        shape = RoundedCornerShape(20),
                        enabled = false,
                        colors = TextFieldDefaults.colors(
                            disabledContainerColor = Color(0xFFF2D6FA),
                            disabledTextColor = 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
                                    save.value = true
                                }
                            )
                        }
                    }
                }

                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))

                if (save.value) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Button(
                            onClick = {
                                if (newAvatar.value.isEmpty()) {
                                    if (genderId.value == 0) {
                                        viewModel.updatePeople(
                                            firstName.value,
                                            null,
                                            birthDate.value!!
                                        )
                                    } else {
                                        viewModel.updatePeople(
                                            firstName.value,
                                            genderId.value!!,
                                            birthDate.value!!
                                        )
                                    }
                                    f.value = true
                                } else {
                                    viewModel.addAvatar(newAvatar.value)
                                    addAvatar.value = true
                                }
                            },
                            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(5.dp))

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Button(
                        onClick = {
                            viewModel.singOut(context)
                            out.value = true
                        },
                        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 (addAvatar.value) {
            when (userState) {
                is UserState.Loading -> {
                    CircularProgressIndicator()
                }

                is UserState.Success -> {
                    if (genderId.value == 0) {
                        viewModel.updatePeople(
                            firstName.value,
                            null,
                            birthDate.value!!
                        )
                    } else {
                        viewModel.updatePeople(
                            firstName.value,
                            genderId.value!!,
                            birthDate.value!!
                        )
                    }
                    addAvatar.value = false
                    f.value = true
                }

                is UserState.Error -> {
                    val message = (userState as UserState.Error).message
                    Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
                    addAvatar.value = false
                }
            }
        }
    }
    else {
        Box(
            modifier = Modifier.fillMaxSize()
        )
        {
            CircularProgressIndicator()
        }
    }
    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
                save.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
            }
        }
    }
}


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()
}

fun ByteArrayImage(byteArray: ByteArray): ImageBitmap {
    // Конвертируем массив байтов в Bitmap с уменьшением масштаба
    val options = BitmapFactory.Options().apply {
        inJustDecodeBounds = true // Сначала считываем только размеры изображения
    }
    BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size, options)

    // Рассчитываем inSampleSize для уменьшения изображения
    options.inSampleSize = calculateInSampleSize(options, reqWidth = 300, reqHeight = 200)
    options.inJustDecodeBounds = false // Теперь декодируем само изображение

    // Декодируем уменьшенное изображение
    val bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size, options)

    // Преобразуем Bitmap в ImageBitmap
    return bitmap.asImageBitmap()
}

fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int {
    val (height: Int, width: Int) = options.outHeight to options.outWidth
    var inSampleSize = 1

    if (height > reqHeight || width > reqWidth) {
        val halfHeight: Int = height / 2
        val halfWidth: Int = width / 2

        while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) {
            inSampleSize *= 2
        }
    }
    return inSampleSize
}

