package com.example.pmulabs.screensMobile

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerColors
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import com.example.pmulabs.basecomponents.navigate.BottomBar
import com.example.pmulabs.basecomponents.navigate.BottomBarScreen
import com.example.pmulabs.basecomponents.navigate.SearchAppBar
import com.example.pmulabs.basecomponents.navigate.TopBar
import com.example.pmulabs.designElem.items.ArticleItem
import com.example.pmulabs.graphs.HomeNavGraph
import com.example.pmulabs.viewModels.AppViewModelProvider
import com.example.pmulabs.viewModels.ArticlePageScreenViewModel
import com.example.pmulabs.viewModels.ArticleScreenViewModel
import com.example.pmulabs.viewModels.CurrentUserViewModel
import com.example.pmulabs.viewModels.SearchViewModel
import com.example.pmulabs.viewModels.SearchWidget
import com.example.pmulabs.viewModels.TagItemViewModel
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date

@Composable
fun MainScreen(navController: NavController, modifier: Modifier = Modifier, articleScreenViewModel: ArticleScreenViewModel = viewModel(factory = AppViewModelProvider.Factory), currentUserViewModel: CurrentUserViewModel = viewModel(factory = AppViewModelProvider.Factory)){
    val articles = articleScreenViewModel.articles.collectAsLazyPagingItems()
    LazyColumn(
        modifier=Modifier
            .background(Color.White)
            .fillMaxSize(),
        contentPadding = PaddingValues(top=75.dp, bottom = 70.dp, start = 10.dp,end=10.dp),
        verticalArrangement = Arrangement.spacedBy(15.dp)){
        items(count = articles.itemCount) { index ->
            val article = articles[index]
            if (article != null) {
                ArticleItem(navController=navController,article = article, currentUserViewModel = currentUserViewModel, onArticleClick = {navController.navigate(BottomBarScreen.ArticlePage.passId(article.id.toString()))})
            }
        }
        articles.apply {
            when {
                loadState.refresh is LoadState.Loading -> {
                    item { CircularProgressIndicator(modifier = Modifier.fillParentMaxSize(), color = Color(0xff423a99)) }
                }
                loadState.append is LoadState.Loading -> {
                    item { CircularProgressIndicator(modifier = Modifier.fillParentMaxSize(), color = Color(0xff423a99)) }
                }
                loadState.refresh is LoadState.Error -> {
                    val err = articles.loadState.refresh as LoadState.Error
                    item { Text(err.error.localizedMessage) }
                }
                loadState.append is LoadState.Error -> {
                    val err = articles.loadState.append as LoadState.Error
                    item { Text(err.error.localizedMessage) }
                }
            }
        }
    }
}

@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LoadScreen(navController: NavHostController=rememberNavController(),articlePageScreenViewModel: ArticlePageScreenViewModel, tagItemViewModel: TagItemViewModel, articleScreenViewModel: ArticleScreenViewModel, searchViewModel: SearchViewModel, currentUserViewModel: CurrentUserViewModel){

    val searchWidgetState by searchViewModel.searchWidgetState
    val searchTextState by searchViewModel.searchTextState
    val formatter = SimpleDateFormat("dd-MMMM-YY")

    val calendar = Calendar.getInstance()
    calendar.set(2023,10,23)

    // set the initial date
    val datePickerState = rememberDatePickerState(initialSelectedDateMillis = calendar.timeInMillis)

    var showDatePicker by remember {
        mutableStateOf(false)
    }

    var selectedDate by remember {
        mutableLongStateOf(calendar.timeInMillis) // or use mutableStateOf(calendar.timeInMillis)
    }

    if (showDatePicker) {
        DatePickerDialog(
            colors= DatePickerColors(
                containerColor = Color.White,
                currentYearContentColor=Color(0xff423a99),
                dateTextFieldColors = TextFieldDefaults.textFieldColors(
                    Color(0xff423a99),
                    containerColor = Color.White,
                    focusedLabelColor = Color(0xff423a99),
                    focusedPlaceholderColor = Color(0xff423a99),
                    focusedTrailingIconColor = Color(0xff423a99)
                ),
                dayContentColor=Color(0xff423a99),
                dayInSelectionRangeContainerColor=Color(0xff423a99),
                dayInSelectionRangeContentColor=Color(0xff423a99),
                disabledDayContentColor=Color(0xff423a99),
                disabledSelectedDayContainerColor=Color(0xff423a99),
                disabledSelectedDayContentColor=Color(0xff423a99),
                disabledSelectedYearContainerColor=Color(0xff423a99),
                disabledSelectedYearContentColor=Color(0xff423a99),
                disabledYearContentColor=Color(0xff423a99),
                dividerColor=Color(0xff423a99),
                headlineContentColor=Color(0xff423a99),
                navigationContentColor=Color(0xff423a99),
                selectedDayContainerColor=Color(0xff423a99),
                selectedDayContentColor=Color.White,
                selectedYearContainerColor=Color(0xff423a99),
                selectedYearContentColor=Color.White,
                subheadContentColor=Color(0xff423a99),
                titleContentColor=Color(0xff423a99),
                todayContentColor=Color(0xff423a99),
                todayDateBorderColor=Color(0xff423a99),
                weekdayContentColor=Color(0xff423a99),
                yearContentColor=Color(0xff423a99)
            ),
            onDismissRequest = {
                showDatePicker = false
            },
            confirmButton = {
                TextButton(
                    modifier=Modifier
                        .background(Color.White),
                    colors = ButtonColors(
                        contentColor = Color(0xff423a99),
                        containerColor=Color.Transparent,
                        disabledContainerColor=Color.Transparent,
                        disabledContentColor= Color.Transparent
                    ),
                    onClick = {
                    showDatePicker = false
                    selectedDate = datePickerState.selectedDateMillis!!
                    Log.d("Selected date: ", formatter.format(Date(selectedDate)))
                        navController.navigate(BottomBarScreen.Calendar.passDate(formatter.format(Date(selectedDate)))){
                            popUpTo(BottomBarScreen.Main.route)
                        }
                }) {
                    Text(text = "Confirm")
                }
            },
            dismissButton = {
                TextButton(
                    modifier=Modifier
                        .background(Color.White),
                    colors = ButtonColors(
                        contentColor = Color(0xff423a99),
                        containerColor=Color.Transparent,
                        disabledContainerColor=Color.Transparent,
                        disabledContentColor= Color.Transparent
                    ),
                    onClick = {
                        showDatePicker = false
                        navController.navigate(BottomBarScreen.Main.route)
                }) {
                    Text(text = "Cancel")
                }
            }
        ) {
            DatePicker(
                modifier= Modifier
                    .background(Color.White)
                    .clip(RoundedCornerShape(15.dp)),
                colors = DatePickerColors(
                        containerColor = Color.White,
                        currentYearContentColor=Color(0xff423a99),
                        dateTextFieldColors = TextFieldDefaults.textFieldColors(
                            Color(0xff423a99),
                            containerColor = Color.White,
                            focusedLabelColor = Color(0xff423a99),
                            focusedPlaceholderColor = Color(0xff423a99),
                            focusedTrailingIconColor = Color(0xff423a99)
                        ),
                        dayContentColor=Color(0xff423a99),
                        dayInSelectionRangeContainerColor=Color(0xff423a99),
                        dayInSelectionRangeContentColor=Color(0xff423a99),
                        disabledDayContentColor=Color(0xff423a99),
                        disabledSelectedDayContainerColor=Color(0xff423a99),
                        disabledSelectedDayContentColor=Color(0xff423a99),
                        disabledSelectedYearContainerColor=Color(0xff423a99),
                        disabledSelectedYearContentColor=Color(0xff423a99),
                        disabledYearContentColor=Color(0xff423a99),
                        dividerColor=Color(0xff423a99),
                        headlineContentColor=Color(0xff423a99),
                        navigationContentColor=Color(0xff423a99),
                        selectedDayContainerColor=Color(0xff423a99),
                        selectedDayContentColor=Color.White,
                        selectedYearContainerColor=Color(0xff423a99),
                        selectedYearContentColor=Color.White,
                        subheadContentColor=Color(0xff423a99),
                        titleContentColor=Color(0xff423a99),
                        todayContentColor=Color(0xff423a99),
                        todayDateBorderColor=Color(0xff423a99),
                        weekdayContentColor=Color(0xff423a99),
                        yearContentColor=Color(0xff423a99)
                ),
                state = datePickerState
            )
        }
    }

    Scaffold(
        bottomBar = { BottomBar(navController = navController) },
        topBar = { MainAppBar(searchWidgetState= searchWidgetState,
            searchTextState= searchTextState,
            onTextChange= { searchViewModel.updateSearchTextState(newValue = it)
                if(it!="") {
                    navController.navigate(BottomBarScreen.Search.passText(it))
                }},
            onCloseClicked= {
                searchViewModel.updateSearchWidgetState(newValue = SearchWidget.CLOSED)
                navController.navigate(BottomBarScreen.Main.route)
            },
            onSearchClicked= {
                navController.navigate(BottomBarScreen.Search.passText(it))
            },
            onSearchTriggered= {
                searchViewModel.updateSearchWidgetState(newValue = SearchWidget.OPENED)
            },
            onCalendarTriggered = {
                showDatePicker = true
            })}
    ) {
        Modifier
            .padding(it)
        HomeNavGraph(navController = navController,articlePageScreenViewModel, tagItemViewModel,articleScreenViewModel,currentUserViewModel)
    }
}

@Composable
fun MainAppBar(
    searchWidgetState: SearchWidget,
    searchTextState: String,
    onTextChange: (String) -> Unit,
    onCloseClicked: () -> Unit,
    onSearchClicked: (String) -> Unit,
    onSearchTriggered: () -> Unit,
    onCalendarTriggered: () -> Unit
) {
    when (searchWidgetState) {
        SearchWidget.CLOSED -> {
            TopBar(
                onSearchClicked = onSearchTriggered,
                onCalendarClicked = onCalendarTriggered
            )
        }
        SearchWidget.OPENED -> {
            SearchAppBar(
                text = searchTextState,
                onTextChange = onTextChange,
                onCloseClicked = onCloseClicked,
                onSearchClicked = onSearchClicked
            )
        }
    }
}




