package com.example.lectionsupabase.view.mainActivity.components

import androidx.compose.material3.ButtonDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.navigation.NavHostController
import com.example.lectionsupabase.domain.utils.Constants
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowForward
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.runtime.LaunchedEffect
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.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImagePainter
import coil.compose.rememberAsyncImagePainter
import coil.compose.rememberImagePainter
import coil.request.ImageRequest
import coil.size.Size
import com.example.lectionsupabase.R
import com.example.lectionsupabase.model.Benchs
import com.example.lectionsupabase.model.Cars
import com.example.lectionsupabase.model.Concerts
import com.example.lectionsupabase.model.Dealers
import com.example.lectionsupabase.model.Restaurants
import io.github.jan.supabase.postgrest.from
import io.github.jan.supabase.storage.BucketItem
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun InsertBench(navHost: NavHostController) {
    val context = LocalContext.current
    val supabase = Constants.supabase
    val scope = rememberCoroutineScope()

    // Поля для ввода данных о лавочках
    val district = remember { mutableStateOf("") }
    val coordinates = remember { mutableStateOf("") }
    val state = remember { mutableStateOf("") }
    val pictureUrl = remember { mutableStateOf("") }
    val showSuccessMessage = remember { mutableStateOf(false) } // Для вывода сообщения
    val montserratRegular = FontFamily(Font(R.font.mon_regular))
    val montserratSemiBold = FontFamily(Font(R.font.mon_semibold))

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        Spacer(modifier = Modifier.height(24.dp))
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 16.dp),
            contentAlignment = Alignment.Center // Центрируем содержимое
        ) {
            Text(
                text = "Добавить лавочку",
                style = MaterialTheme.typography.headlineMedium,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.onBackground,
                fontSize = 20.sp,
                fontFamily = montserratSemiBold,
            )
        }

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

        // Поля ввода
        OutlinedTextField(
            value = district.value,
            onValueChange = { district.value = it },
            label = {
                Text(
                    text = "Район",
                    fontSize = 14.sp,
                    fontFamily = montserratRegular
                )
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 8.dp),
            singleLine = true,
            shape = RoundedCornerShape(8.dp),
            colors = TextFieldDefaults.outlinedTextFieldColors(
                focusedLabelColor = Color.Black,
                unfocusedLabelColor = Color.Gray
            )
        )

        OutlinedTextField(
            value = coordinates.value,
            onValueChange = { coordinates.value = it },
            label = {
                Text(
                    text = "Координаты",
                    fontSize = 14.sp,
                    fontFamily = montserratRegular
                )
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 8.dp),
            singleLine = true,
            shape = RoundedCornerShape(8.dp),
            colors = TextFieldDefaults.outlinedTextFieldColors(
                focusedLabelColor = Color.Black,
                unfocusedLabelColor = Color.Gray
            )
        )

        OutlinedTextField(
            value = state.value,
            onValueChange = { state.value = it },
            label = {
                Text(
                    text = "Состояние",
                    fontSize = 14.sp,
                    fontFamily = montserratRegular
                )
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 8.dp),
            singleLine = true,
            shape = RoundedCornerShape(8.dp),
            colors = TextFieldDefaults.outlinedTextFieldColors(
                focusedLabelColor = Color.Black,
                unfocusedLabelColor = Color.Gray
            )
        )

        OutlinedTextField(
            value = pictureUrl.value,
            onValueChange = { pictureUrl.value = it },
            label = {
                Text(
                    text = "Ссылка на изображение",
                    fontSize = 14.sp,
                    fontFamily = montserratRegular
                )
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 8.dp),
            singleLine = true,
            shape = RoundedCornerShape(8.dp),
            colors = TextFieldDefaults.outlinedTextFieldColors(
                focusedLabelColor = Color.Black,
                unfocusedLabelColor = Color.Gray
            )
        )

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

        // Кнопка добавления
        Button(
            onClick = {
                scope.launch {
                    // Получаем количество записей и добавляем новую лавочку
                    val count = supabase.from("Benchs").select().decodeList<Benchs>().size
                    val newBench = Benchs(
                        id = count + 1, // Предполагаем, что id - это автоинкрементное поле
                        district = district.value,
                        coordinates = coordinates.value,
                        state = state.value,
                        picture = pictureUrl.value.ifBlank { null }
                    )

                    // Встав // Вставляем новую лавочку в базу данных
                    supabase.from("Benchs").insert(newBench)

                    Toast.makeText(context, "Лавочка добавлена", Toast.LENGTH_LONG).show()
                    showSuccessMessage.value = true

                    // Возврат на экран лавочек
                    navHost.navigate("Benchs") {
                        popUpTo("Benchs") { inclusive = true }
                    }
                }
            },
            modifier = Modifier
                .fillMaxWidth()
                .height(56.dp),
            shape = RoundedCornerShape(8.dp),
            colors = ButtonDefaults.buttonColors(
                containerColor = Color(0XFFA3D5F1),
                contentColor = Color.White
            )
        ) {
            Text("Добавить лавочку", fontSize = 16.sp)
        }

        // Сообщение об успешном добавлении
        if (showSuccessMessage.value) {
            Text(
                text = "Лавочка успешно добавлена!",
                color = Color.Black,
                modifier = Modifier.padding(top = 8.dp)
            )
        }
    }
}