package com.example.what_the_fantasy.ui.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
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.data.model.Quote
import com.example.what_the_fantasy.data.services.IServices
import com.example.what_the_fantasy.ui.components.NavBar
import com.example.what_the_fantasy.ui.components.QuoteLittle
import com.example.what_the_fantasy.ui.states.CurrentUserState
import com.example.what_the_fantasy.ui.viewModels.CurrentUserViewModel
import kotlinx.coroutines.delay

@Composable
fun SearchPage(
    navFavorite: () -> Unit,
    navAccueil: () -> Unit,
    navProfil: () -> Unit,
    navQuiz: () -> Unit,
    navQuote: (Int) -> Unit,
    navSearch: (String, String) -> Unit,
    services: IServices,
    type: String,
    search: String,
    currentUserVM : CurrentUserViewModel,
    currentUserState : CurrentUserState,
) {
    var newSearch by remember { mutableStateOf(search) }
    val filtre = listOf("contenue", "personnage", "titre")
    val (newFiltre, onFiltreSelected) = remember { mutableStateOf(type) }

    val page = remember { mutableStateOf(1) }
    val quotes = remember { mutableStateListOf<Quote>() }
    val isLoading = remember { mutableStateOf(false) }
    val state = rememberLazyListState()

    LaunchedEffect(page.value, type, search) {
        if (!isLoading.value) {
            isLoading.value = true
            delay(500)
            val newQuotes = services.search(type, search, page.value * 15)
            val uniqueQuotes = newQuotes.filterNot { new -> quotes.any { it.id == new.id } }
            if (uniqueQuotes.isNotEmpty()) {
                quotes.addAll(uniqueQuotes)
            }
            isLoading.value = false
        }
    }

    NavBar(
        onAccueil = true,
        navControllerFavorite = navFavorite,
        navControllerAccueil = navAccueil,
        navControllerProfil = navProfil,
        navControllerQuiz = navQuiz,
        navControllerSearch = { navSearch("contenue", "") },
        currentUserVM = currentUserVM,
        currentUserState = currentUserState,

    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(MaterialTheme.colorScheme.background)
        ) {
            Text(
                text = "▶ " + stringResource(R.string.TitleSearch) + " ◀",
                color = MaterialTheme.colorScheme.onBackground,
                fontSize = 24.sp,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                textAlign = TextAlign.Center
            )
            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                OutlinedTextField(
                    value = newSearch,
                    onValueChange = { newSearch = it },
                    textStyle = TextStyle(color = MaterialTheme.colorScheme.onBackground),
                    modifier = Modifier
                        .padding(top = 2.dp)
                        .fillMaxWidth()
                        .height(50.dp),
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
                    maxLines = 1,
                    shape = CircleShape,
                    trailingIcon = {
                        IconButton(
                            onClick = { navSearch(newFiltre, newSearch) },
                            modifier = Modifier
                                .size(50.dp)
                                .clip(CircleShape)
                        ) {
                            Icon(
                                Icons.Rounded.Search,
                                contentDescription = stringResource(R.string.TitleSearch),
                                Modifier
                                    .fillMaxSize()
                                    .background(MaterialTheme.colorScheme.primary, CircleShape)
                            )
                        }
                    }
                )
                Row(horizontalArrangement = Arrangement.SpaceAround) {
                    filtre.forEach { typeItem ->
                        Row(
                            Modifier
                                .height(56.dp)
                                .selectable(
                                    selected = (typeItem == newFiltre),
                                    onClick = { onFiltreSelected(typeItem) },
                                    role = Role.RadioButton
                                )
                                .padding(horizontal = 16.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            RadioButton(
                                selected = (typeItem == newFiltre),
                                onClick = null
                            )
                            Text(
                                text = typeItem,
                                style = MaterialTheme.typography.bodyLarge,
                                modifier = Modifier.padding(start = 16.dp),
                                color = MaterialTheme.colorScheme.onBackground
                            )
                        }
                    }
                }
            }
            LazyColumn(
                modifier = Modifier.weight(1f),
                state = state
            ) {
                items(quotes) { quote ->
                    Column(Modifier.clickable { navQuote(quote.id) }) {
                        QuoteLittle(quote)
                    }
                }
                item {
                    if (state.layoutInfo.visibleItemsInfo.lastOrNull()?.index == quotes.size - 1 && !isLoading.value) {
                        LaunchedEffect(Unit) {
                            page.value++
                        }
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp),
                            contentAlignment = Alignment.Center
                        ) {
                            CircularProgressIndicator()
                        }
                    }
                }
            }
        }
    }
}
