package com.example.what_the_fantasy.ui.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
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.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.what_the_fantasy.R
import com.example.what_the_fantasy.ui.components.ErrorMessageSubmitQuoteComponent
import com.example.what_the_fantasy.ui.components.NavBar
import com.example.what_the_fantasy.ui.components.SpaceHeightComponent
import com.example.what_the_fantasy.ui.components.TitlePageComponent
import com.example.what_the_fantasy.ui.states.CurrentUserState
import com.example.what_the_fantasy.ui.theme.colorBackground
import com.example.what_the_fantasy.ui.theme.gradienBox
import com.example.what_the_fantasy.ui.viewModels.CurrentUserViewModel

@Composable
fun SubmitQuotePage(
    navFavorite: () -> Unit,
    navAccueil: () -> Unit,
    navProfil:() -> Unit,
    navQuiz: () -> Unit,
    navRecap: (String, String, String) -> Unit,
    currentUserVM : CurrentUserViewModel,
    currentUserState : CurrentUserState,
) {
    NavBar(
        currentUserVM = currentUserVM,
        currentUserState = currentUserState,
        navControllerFavorite = navFavorite,
        navControllerAccueil = navAccueil,
        navControllerProfil = navProfil,
        navControllerQuiz = navQuiz
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(MaterialTheme.colorScheme.background)
                .verticalScroll(rememberScrollState()),
            contentAlignment = Alignment.Center
        ){
            Column(
                modifier = Modifier
                    .fillMaxWidth(0.9f)
                    .padding(20.dp)
                    .clip(RoundedCornerShape(16.dp))
                    .background(MaterialTheme.colorScheme.onPrimary)
                    .padding(20.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                TitlePageComponent(R.string.titleSubmitQuote, MaterialTheme.colorScheme.onBackground)
                SpaceHeightComponent(20)
                SubmitQuoteButton(
                    quoteTextField(R.string.quote),
                    characterTextField(R.string.character),
                    sourceTextField(R.string.source),
                    timeCodeTextField(R.string.timeCode),
                    yearTextField(R.string.year),
                    R.string.titleButtonSubmit,
                    18,
                    MaterialTheme.colorScheme.background,
                    MaterialTheme.colorScheme.onBackground,
                    navRecap
                )
                SpaceHeightComponent(20)
                BackButton(R.string.titleButtonBack, 12, Color.White,navProfil)
            }
        }
    }
    
}

@Composable
fun quoteTextField(textQuoteResId : Int) : String{
    val textQuote = stringResource(id = textQuoteResId)
    var quote by remember { mutableStateOf("") }
    Column(modifier = Modifier.padding(top = 16.dp)) {
        OutlinedTextField(
            value = quote,
            onValueChange = { quote = it },
            label = { Text(textQuote, color = MaterialTheme.colorScheme.onBackground) },
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 8.dp),
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
            shape = RoundedCornerShape(16.dp)
        )
    }
    return quote;
}

@Composable
fun characterTextField(textCharacterResId : Int) : String{
    val textCharacter = stringResource(id = textCharacterResId)
    var character by remember { mutableStateOf("") }

    Column(modifier = Modifier.padding(top = 16.dp)) {
        OutlinedTextField(
            value = character,
            onValueChange = { character = it },
            label = { Text(textCharacter, color = MaterialTheme.colorScheme.onBackground) },
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 8.dp),
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
            shape = RoundedCornerShape(16.dp) 
        )
    }
    return character;
}

@Composable
fun sourceTextField(textSourceResId : Int) : String{
    val textSource = stringResource(id = textSourceResId)
    var source by remember { mutableStateOf("") }
    Column(modifier = Modifier.padding(top = 16.dp)) {
        OutlinedTextField(
            value = source,
            onValueChange = { source = it },
            label = { Text(textSource, color = MaterialTheme.colorScheme.onBackground) },
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 8.dp),
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
            shape = RoundedCornerShape(16.dp) 
        )
    }
    return source;
}


@Composable
fun timeCodeTextField(textTimeCodeResId : Int) : String{
    val textTimeCode = stringResource(id = textTimeCodeResId)
    var timeCode by remember { mutableStateOf("") }
    Column(modifier = Modifier.padding(top = 16.dp)) {
        OutlinedTextField(
            value = timeCode,
            onValueChange = { timeCode = it },
            label = { Text(textTimeCode, color = MaterialTheme.colorScheme.onBackground) },
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 8.dp),
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
            shape = RoundedCornerShape(16.dp) 
        )
    }
    return timeCode;
}


@Composable
fun yearTextField(textYearResId : Int) : String{
    val textYear = stringResource(id = textYearResId)
    var year by remember { mutableStateOf("") }
    Column(modifier = Modifier.padding(top = 16.dp, bottom = 30.dp)) {
        OutlinedTextField(
            value = year,
            onValueChange = { year = it },
            label = { Text(textYear, color = MaterialTheme.colorScheme.onBackground) },
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 8.dp),
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
            shape = RoundedCornerShape(16.dp) 
        )
    }
    return year;
}


@Composable
fun SubmitQuoteButton(
    quote: String,
    character: String,
    source: String,
    timeCode: String,
    year: String,
    titleResId: Int,
    size: Int,
    colorButton: Color,
    colorText: Color,
    navRecap : (String, String, String) -> Unit
) {
    val title = stringResource(id = titleResId)
    var showError by remember { mutableStateOf(false) }

    Button(
        onClick = { showError = !goToRecap(quote, character, source, timeCode, year, navRecap) },
        colors = ButtonDefaults.buttonColors(containerColor = colorButton),
        modifier = Modifier.fillMaxWidth(),
    ) {
        Text(title, fontSize = size.sp, color = colorText)
    }

    if (showError) {
        ErrorMessageSubmitQuoteComponent(R.string.ErrorSubmitQuote)
    }
}

fun goToRecap(quote: String,
              character: String,
              source: String,
              timeCode: String,
              year: String,
              navRecap : (String, String, String) -> Unit): Boolean {
    if (validSubmitQuote(quote, character, source, timeCode, year)) {
        navRecap(quote, character, source)
        return true
    }
    return false
}

fun validSubmitQuote(quote : String, character : String, source: String, timeCode: String, year: String): Boolean{

    val quoteRegex = """^[A-Za-zÀ-ÿ0-9\s\-\.,!?'"()]+$""".toRegex()
    val timeCodeRegex = """^\d{1}:\d{2}:\d{2}$""".toRegex()
    val movieTitleRegex = """^[A-Za-z0-9\s\-\(\):]+$""".toRegex()
    val characterRegex = """^[A-Za-zÀ-ÿ\s\-']+$""".toRegex()
    val invalidRegex = """^[a-zA-Z0-9]*$""".toRegex()

    val isNotBlank = quote.isNotBlank() && quote.matches(quoteRegex) && !quote.matches(invalidRegex) && quote.length in 3..100 &&
            character.isNotBlank() && character.matches(characterRegex) && character.length in 3..50 && /*!character.matches(invalidRegex) &&*/
            source.isNotBlank() && source.matches(movieTitleRegex) && source.length in 3..50 && /*!source.matches(invalidRegex) &&*/
            timeCode.isNotBlank() && timeCode.matches(timeCodeRegex) &&
            year.isNotBlank() && year.all { it.isDigit() } && year.length == 4 && year.toInt() in 1900..2025
    return isNotBlank
}

@Composable
fun BackButton(titleResId : Int, size : Int, color : Color, navController: () -> Unit) {
    val title = stringResource(id = titleResId)
    Text(
        text = title,
        fontSize = size.sp,
        color = color,
        modifier = Modifier.clickable {
            navController()
        }
    )
}

