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.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.tooling.preview.Preview
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.UserState
import com.example.tasks.navigation.Screen
import com.example.tasks.viewModels.DatabaseViewModel


@Composable
fun AddProducts(viewModel: DatabaseViewModel,navController: NavController) {
    val avatar = remember { mutableStateOf(byteArrayOf()) }
    val userState by viewModel.userState
    val urii = remember { mutableStateOf("") }
    val title = remember { mutableStateOf("") }
    val titleFlag = remember { mutableStateOf(false) }
    val description = remember { mutableStateOf("") }
    val price = remember { mutableStateOf("") }
    val currentUserState = remember { mutableStateOf("") }
    val priceFlag = remember { mutableStateOf(false) }
    val enabled = remember { mutableStateOf(false) }
    val flag = remember { mutableStateOf(false) }
    val flag2 = remember { mutableStateOf(false) }
    val context = LocalContext.current
    val launcher =
        rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri == null) return@rememberLauncherForActivityResult
            avatar.value = bitmapToByteArray(context, uri)
            urii.value = uri.schemeSpecificPart

        }
    if(!titleFlag.value && !priceFlag.value){
        enabled.value = true
    }
    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(40.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)
            }
        }
        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)
                )
            }
        )

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

        Spacer(modifier = Modifier.height(20.dp))
        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

    ) {
        Button(
            modifier = Modifier
                .width(width = 500.dp)
                .height(height = 56.dp),
            onClick = {
                viewModel.addAvatar(avatar.value)
                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
                viewModel.addProducts(title.value, description.value, price.value.toDouble())
                flag.value = false
                flag2.value = true
            }

            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)
        }
    }
    if (flag2.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)
                flag2.value = false
            }

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

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