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.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
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.local.DailyQuoteStub
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 com.example.what_the_fantasy.ui.theme.colorBackground
import kotlinx.coroutines.delay

@Composable
fun AccueilPage(
    navFavorite: () -> Unit,
    navQuiz: () -> Unit,
    navProfil: () -> Unit,
    navQuote: (Int) -> Unit,
    navSearch: () -> Unit,
    services: IServices,
    currentUserVM : CurrentUserViewModel,
    currentUserState : CurrentUserState,

) {
    val dailyQuote = DailyQuoteStub.dailyQuote

    val titleDalyQuote = stringResource(R.string.TitleHomeDailyQuote)
    val titleSuggestion = stringResource(R.string.TitleHomeSuggestion)

    val page = remember { mutableIntStateOf(1) }
    val quotes = remember { mutableStateListOf<Quote>() }
    val state = rememberLazyListState()
    val layoutInfo = remember { derivedStateOf { state.layoutInfo } }
    val isLoading = remember { mutableStateOf(false) }
    val visibleItemsInfo = layoutInfo.value.visibleItemsInfo
    val fullyVisibleItemsInfo = visibleItemsInfo.toMutableList()
    val lastItem = if (fullyVisibleItemsInfo.isNotEmpty()) fullyVisibleItemsInfo.last() else null


    LaunchedEffect(page.intValue) {
        if (!isLoading.value) {
            isLoading.value = true
            delay(500)
            val newQuotes = services.getSomeQuotes(15, page.intValue)
            val uniqueQuotes = newQuotes.filterNot { new -> quotes.any { it.id == new.id } }

            if (uniqueQuotes.isNotEmpty()) {
                quotes.addAll(uniqueQuotes)
            } else {
                println("Aucune nouvelle quote à la page ${page.intValue}, stop pagination.")
            }
            isLoading.value = false
        }
    }



    NavBar(
        onAccueil = true,
        currentUserVM = currentUserVM,
        currentUserState = currentUserState,
        navControllerFavorite = navFavorite,
        navControllerProfil = navProfil,
        navControllerQuiz = navQuiz,
        navControllerSearch = navSearch
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(MaterialTheme.colorScheme.background)
        ) {
            LazyColumn(modifier = Modifier.weight(1f), state = state) {
                item {
                    Column(Modifier.clickable { navQuote(dailyQuote.id) }) {
                        Text(
                            text = titleDalyQuote,
                            color = MaterialTheme.colorScheme.onBackground,
                            fontSize = 24.sp,
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp),
                            textAlign = TextAlign.Center
                        )
                        QuoteLittle(dailyQuote)
                    }

                    Text(
                        text = titleSuggestion,
                        color = MaterialTheme.colorScheme.onBackground,
                        fontSize = 24.sp,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        textAlign = TextAlign.Center
                    )
                }

                items(quotes) { quote ->
                    if (quote.language == currentUserState.langage) {
                        Column(Modifier.clickable { navQuote(quote.id ) }) {
                            QuoteLittle(quote)
                            Spacer(modifier = Modifier.height(16.dp))
                        }
                    }
                }

                item {
                    if (lastItem?.index == quotes.size) {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp),
                            contentAlignment = Alignment.Center
                        ) {
                            CircularProgressIndicator()
                        }
                    } else {
                        LaunchedEffect(remember { derivedStateOf { state.firstVisibleItemIndex } }, remember { derivedStateOf { state.layoutInfo } }.value.totalItemsCount) {
                            if (!isLoading.value && state.layoutInfo.visibleItemsInfo.isNotEmpty()) {
                                val lastVisibleItem = state.layoutInfo.visibleItemsInfo.last()
                                if (lastVisibleItem.index >= state.layoutInfo.totalItemsCount - 1) {
                                    page.intValue++
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
