package com.example.tasks.screens

import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
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.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.example.tasks.model.UserState
import com.example.tasks.navigation.Screen
import com.example.tasks.viewModels.AuthViewModel
import com.example.tasks.viewModels.DatabaseViewModel
import kotlinx.coroutines.delay


@Composable
fun EnterOTP(
    navController: NavController,
    email: String,
    viewModel: AuthViewModel,
    viewModelDatabase: DatabaseViewModel
) {
    val userState by viewModel.userState
    var currentUserState by remember { mutableStateOf("") }
    val focusManager = LocalFocusManager.current
    val flag = remember { mutableStateOf(false) }
    val flag1 = remember { mutableStateOf(false) }
    val context = LocalContext.current
    val keyboardController = LocalSoftwareKeyboardController.current

    val textList = listOf(
        remember {
            mutableStateOf(
                TextFieldValue(
                    text = "",
                    selection = TextRange(0)
                )
            )
        },
        remember {
            mutableStateOf(
                TextFieldValue(
                    text = "",
                    selection = TextRange(0)
                )
            )
        },
        remember {
            mutableStateOf(
                TextFieldValue(
                    text = "",
                    selection = TextRange(0)
                )
            )
        },
        remember {
            mutableStateOf(
                TextFieldValue(
                    text = "",
                    selection = TextRange(0)
                )
            )
        },
        remember {
            mutableStateOf(
                TextFieldValue(
                    text = "",
                    selection = TextRange(0)
                )
            )
        },
        remember {
            mutableStateOf(
                TextFieldValue(
                    text = "",
                    selection = TextRange(0)
                )
            )
        }

    )

    val requesterList = listOf(
        remember { FocusRequester() },
        remember { FocusRequester() },
        remember { FocusRequester() },
        remember { FocusRequester() },
        remember { FocusRequester() },
        remember { FocusRequester() }

    )
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0xFF951DDD))
            .pointerInput(Unit) {
                detectTapGestures(onTap = {
                    keyboardController?.hide()
                    focusManager.clearFocus()
                })
            }
    )
    {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 60.dp, start = 20.dp),
            horizontalArrangement = Arrangement.Start,
            verticalAlignment = Alignment.Top
        ) {
            Button(
                onClick = { navController.navigate(Screen.SignIn.route) },
                shape = RoundedCornerShape(size = 8.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(0xFFF5F5F9)
                ),
                modifier = Modifier
                    .width(32.dp)
                    .height(32.dp), contentPadding = PaddingValues(1.dp)
            )
            {
                Icon(
                    imageVector = Icons.AutoMirrored.Filled.KeyboardArrowLeft,
                    contentDescription = "Назад",
                    tint = Color.Black,
                    modifier = Modifier.size(20.dp)
                )
            }
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(text = "Введите код из E-mail", fontSize = 20.sp, color = Color.White, fontWeight = FontWeight.Black)
        Row(
            modifier = Modifier
                .align(Alignment.CenterHorizontally)
        ) {
            ContentView(textList, requesterList)
        }
        Spacer(modifier = Modifier.height(30.dp))
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 10.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        )
        {

            var timer by remember { mutableIntStateOf(60) }
            LaunchedEffect(key1 = timer) {
                if (timer > 0) {
                    delay(1_000)
                    timer -= 1
                }
            }
            if (timer != 0) {
                Text(
                    text = "Отправить код повторно можно",
                    fontSize = 15.sp,
                    color = Color.White
                )
                Text(
                    text = "будет через $timer секунд",
                    fontSize = 15.sp,
                    color = Color.White
                )

            } else {
                Text(
                    text = "Отправить код заново",
                    fontSize = 15.sp,
                    color = Color.White,
                    modifier = Modifier.clickable {
                        viewModel.onSignInEmailCode(context, email)
                        timer = 60
                    }
                )
            }

        }

        Button(
            onClick = {
                val token = token(textList)
                viewModel.verifyOTP(email, token)
                flag.value = true
            },
            Modifier
                .fillMaxWidth(0.9f)
                .height(50.dp)
                .padding(top =10.dp),
            shape = RoundedCornerShape(20),
            colors = ButtonColors(
                contentColor = Color(0xFF951DDD),
                containerColor = Color.White,
                disabledContentColor = Color(0xFF951DDD),
                disabledContainerColor = Color.LightGray
            )
        ) {
            Text(text = "Далее", fontSize = 14.sp)

        }
        if (flag.value) {
            when (userState) {
                is UserState.Loading -> {
                    LoadingComponent()
                }

                is UserState.Success -> {
                    viewModel.checkForRegistration()
                    flag.value = false
                    flag1.value = true
                }

                is UserState.Error -> {
                    val message = (userState as UserState.Error).message
                    currentUserState = message
                    Toast.makeText(context, "Неверный код", Toast.LENGTH_SHORT).show()
                    flag.value = false
                }
            }

            if (currentUserState.isNotEmpty()) {
                Log.d("my_tag",currentUserState)
            }
        }

        if (flag1.value) {
            when (userState) {
                is UserState.Loading -> {
                    LoadingComponent()
                }

                is UserState.Success -> {
                    if (viewModel.users.isNotEmpty()) {
                        navController.navigate(Screen.AppNavigationCustomers.route)
                        viewModelDatabase.profileData()
                    } else {
                        if (viewModel.sellers.isEmpty()) {
                            navController.navigate(Screen.CreateProfile.route)
                        } else {
                            navController.navigate(Screen.AppNavigationSellers.route)
                            viewModelDatabase.profileDataSeller()
                        }
                    }

                    flag1.value = false
                }

                is UserState.Error -> {

                    val message = (userState as UserState.Error).message
                    currentUserState = message
                    flag1.value = false
                }
            }

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

    }

}

@Composable
fun LoadingComponent() {
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        CircularProgressIndicator()
    }
}

private fun token(textList: List<MutableState<TextFieldValue>>): String {
    var code = ""
    for (text in textList) {
        code += text.value.text
    }
    return code
}


fun nextFocus(
    textList: List<MutableState<TextFieldValue>>,
    requesterList: List<FocusRequester>
) {
    for (index in textList.indices) {
        if (textList[index].value.text == "") {
            if (index < textList.size) {
                requesterList[index].requestFocus()
                break
            }
        }
    }
}

@Composable
fun inputWiew(
    value: TextFieldValue,
    onValueChange: (value: TextFieldValue) -> Unit,
    focusRequester: FocusRequester
) {
    BasicTextField(
        readOnly = false,
        value = value,
        onValueChange = onValueChange,

        modifier = Modifier
            .clip(RoundedCornerShape(10.dp))
            .padding(horizontal = 7.dp)
            .clip(RoundedCornerShape(8.dp))
            .wrapContentSize()
            .background(Color(0xFFF5F5F9))
            .focusRequester(focusRequester)
            .border(1.dp, Color(0xFFEBEBEB)),
        singleLine = true,
        maxLines = 1,
        decorationBox = { innerTextField ->
            Box(
                modifier = Modifier
                    .width(40.dp)
                    .height(40.dp),
                contentAlignment = Alignment.Center,
            )
            {
                innerTextField()
            }

        },
        cursorBrush = SolidColor(Color.Black),
        textStyle = TextStyle(
            color = Color.Black,
            fontSize = 20.sp,
            textAlign = TextAlign.Center
        ),
        keyboardOptions = KeyboardOptions(
            keyboardType = KeyboardType.Number,
            imeAction = ImeAction.Done
        ),
        keyboardActions = KeyboardActions(
            onDone = null
        )
    )
}

@Composable
fun ContentView(
    textList: List<MutableState<TextFieldValue>>,
    requesterList: List<FocusRequester>,
) {


    Surface {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(Color(0xFF951DDD))
        )
        {
            Row(
                modifier = Modifier
                    .background(Color(0xFF951DDD))
                    .padding(horizontal = 16.dp)
                    .padding(top = 50.dp)
                    .align(Alignment.Center)
            ) {
                for (i in textList.indices) {
                    inputWiew(
                        value = textList[i].value,
                        onValueChange = { newValue ->
                            if (textList[i].value.text != "") {
                                if (newValue.text == "") {
                                    textList[i].value = TextFieldValue(
                                        text = "",
                                        selection = TextRange(0)
                                    )
                                }
                                return@inputWiew
                            }
                            textList[i].value = TextFieldValue(
                                text = newValue.text,
                                selection = TextRange(newValue.text.length)
                            )
                            nextFocus(textList, requesterList)
                        },
                        focusRequester = requesterList[i]
                    )

                }


            }
        }
    }
}





