package com.example.tasks.screens

import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
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.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.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.CircularProgressIndicator
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.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
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.core.text.isDigitsOnly
import androidx.navigation.NavController
import bitmapToByteArray
import com.example.tasks.model.Product
import com.example.tasks.model.UserState
import com.example.tasks.navigation.Screen
import com.example.tasks.viewModels.CardViewModel
import com.example.tasks.viewModels.DatabaseViewModel

@Composable
fun Card( viewModel: DatabaseViewModel,navController: NavController,viewModelCard:CardViewModel) {
    val product = viewModelCard.product
   if(product == null){
       Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center){
           CircularProgressIndicator()
       }
   }
    else{
       val avatar = remember { mutableStateOf(byteArrayOf()) }
       val userState by viewModel.userState
       val title = remember { mutableStateOf(product!!.title) }
       val titleFlag = remember { mutableStateOf(false) }
       val description = remember { mutableStateOf(product!!.description) }
       val description2 = remember { mutableStateOf("") }
       val price = remember { mutableStateOf(product!!.price.toString()) }
       val currentUserState = remember { mutableStateOf("") }
       val priceFlag = remember { mutableStateOf(false) }
       val enabled = remember { mutableStateOf(false) }
       val flag = remember { mutableStateOf(false) }
       val context = LocalContext.current


       Column(
           modifier = Modifier
               .fillMaxSize()
               .background(Color(0xFF951DDD))
               .padding(40.dp),
           verticalArrangement = Arrangement.Top,
           horizontalAlignment = Alignment.CenterHorizontally
       ) {

           Text(
               "Редактирование карточки",
               fontWeight = FontWeight.Black,
               fontSize = 20.sp,
               color = Color.White
           )

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

           OutlinedTextField(value = title.value,
               onValueChange = { title.value = it },
               shape = RoundedCornerShape(5.dp),
               modifier = Modifier
                   .height(height = 56.dp)
                   .width(width = 320.dp),
               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 = titleFlag.value,
               placeholder = {
                   Text(
                       modifier = Modifier.fillMaxWidth(),
                       text = "Название",
                       fontWeight = FontWeight.Normal,
                       fontSize = 15.sp,
                       color = Color(0XFF939396)
                   )
               }
           )

           if (title.value.isEmpty()) {
               titleFlag.value = true
               Text(
                   "Введите название",
                   color = Color(0xFFFEB3F6),
                   fontSize = 10.sp,
                   textAlign = TextAlign.Start
               )
           } else {
               titleFlag.value = false
           }

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

           OutlinedTextField(value = price.value,
               onValueChange = { price.value = it },
               shape = RoundedCornerShape(5.dp),
               modifier = Modifier
                   .height(height = 56.dp)
                   .width(width = 320.dp),
               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 = priceFlag.value,
               placeholder = {
                   Text(
                       modifier = Modifier.fillMaxWidth(),
                       text = "Цена",
                       fontWeight = FontWeight.Normal,
                       fontSize = 15.sp,
                       color = Color(0XFF939396)
                   )
               }
           )
           val isNoLetters = price.value.none { it.isLetter() }

           if (price.value.isEmpty() || !isNoLetters) {
               priceFlag.value = true
               Text("Неверная цена", color = Color(0xFFFEB3F6), fontSize = 10.sp)
           } else {
               priceFlag.value = false
           }

           Spacer(modifier = Modifier.height(20.dp))
           if(description.value == null)
           {
               OutlinedTextField(value = description2.value,
                   onValueChange = { description2.value = it },
                   shape = RoundedCornerShape(5.dp),
                   modifier = Modifier
                       .height(height = 56.dp)
                       .width(width = 320.dp),
                   colors = TextFieldDefaults.colors(
                       focusedContainerColor = Color(0XFFF5F5F9),
                       focusedIndicatorColor = Color(0xFFEBEBEB),
                       focusedTextColor = Color.Black,
                       disabledIndicatorColor = Color.Transparent,
                       unfocusedIndicatorColor = Color.Transparent,
                       cursorColor = Color(0XFF578FFF),
                       focusedSupportingTextColor = Color(0xFF00000)
                   ),
                   placeholder = {
                       Text(
                           modifier = Modifier.fillMaxWidth(),
                           text = "Описание",
                           fontWeight = FontWeight.Normal,
                           fontSize = 15.sp,
                           color = Color(0XFF939396)
                       )
                   }
               )
           }else{
               OutlinedTextField(value = description.value!!,
                   onValueChange = { description.value = it },
                   shape = RoundedCornerShape(5.dp),
                   modifier = Modifier
                       .height(height = 56.dp)
                       .width(width = 320.dp),
                   colors = TextFieldDefaults.colors(
                       focusedContainerColor = Color(0XFFF5F5F9),
                       focusedIndicatorColor = Color(0xFFEBEBEB),
                       focusedTextColor = Color.Black,
                       disabledIndicatorColor = Color.Transparent,
                       unfocusedIndicatorColor = Color.Transparent,
                       cursorColor = Color(0XFF578FFF),
                       focusedSupportingTextColor = Color(0xFF00000)
                   ),
                   placeholder = {
                       Text(
                           modifier = Modifier.fillMaxWidth(),
                           text = "Описание",
                           fontWeight = FontWeight.Normal,
                           fontSize = 15.sp,
                           color = Color(0XFF939396)
                       )
                   }
               )
           }



       }
       Box(
           modifier = Modifier
               .fillMaxSize()
               .clip(RoundedCornerShape(10.dp))
               .padding(40.dp),
           contentAlignment = Alignment.BottomCenter

       ) {
           if(!titleFlag.value && !priceFlag.value){
               enabled.value = true
           }else{
               enabled.value = false
           }
           Button(
               modifier = Modifier
                   .width(width = 500.dp)
                   .height(height = 56.dp),
               onClick = {
                   if(description2.value.isNotEmpty()){
                       viewModel.updateCard(title.value,description2.value, price = price.value.toDouble(),product!!.id!!)
                       flag.value = true
                   }
                   else{
                       viewModel.updateCard(title.value,description.value, price = price.value.toDouble(),product!!.id!!)
                       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 (flag.value) {
           when (userState) {
               is UserState.Loading -> {
                   LoadingComponent()
               }

               is UserState.Success -> {
                   val message = (userState as UserState.Success).message
                   currentUserState.value = message
                   Toast.makeText(context, "Успешно обновлено", Toast.LENGTH_SHORT).show()
                   navController.navigate(Screen.AppNavigationSellers.route)
                   flag.value = false
               }

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

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