package com.pixelized.biblib.ui.screen.home.filter

import android.content.res.Configuration.UI_MODE_NIGHT_NO
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.text.KeyboardActionScope
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.max
import androidx.paging.PagingData
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import com.pixelized.biblib.model.search.FilterType
import com.pixelized.biblib.ui.composable.Handle
import com.pixelized.biblib.ui.theme.BibLibTheme
import com.pixelized.biblib.utils.extention.bibLib
import com.pixelized.biblib.utils.extention.imeHeight
import com.pixelized.biblib.utils.extention.navigationBarsHeight
import kotlinx.coroutines.flow.emptyFlow

@Stable
@Immutable
data class FilterItemUio(
    val id: FilterType,
    val filterId: Int,
    val filterLabel: String,
)

@Composable
fun FilterPage(
    modifier: Modifier,
    viewModel: IFilterViewModel,
    focusRequester: FocusRequester,
    onFilter: (FilterItemUio) -> Unit,
    onIMEDone: KeyboardActionScope.() -> Unit,
) {
    val filters = viewModel.paging.collectAsLazyPagingItems()

    FilterPageContent(
        modifier = modifier,
        focusRequester = focusRequester,
        title = viewModel.title,
        search = viewModel.search,
        onSearchUpdate = { viewModel.updateSearch(it) },
        onClear = { viewModel.updateSearch("") },
        filters = filters,
        onFilter = onFilter,
        onIMEDone = onIMEDone,
    )
}

@Composable
private fun FilterPageContent(
    modifier: Modifier = Modifier,
    focusRequester: FocusRequester,
    title: String,
    search: State<String>,
    onSearchUpdate: (String) -> Unit,
    onClear: () -> Unit,
    filters: LazyPagingItems<FilterItemUio>,
    onFilter: (FilterItemUio) -> Unit,
    onIMEDone: KeyboardActionScope.() -> Unit,
) {
    val navigationBarsHeight = navigationBarsHeight()
    val imeHeight = imeHeight()
    val paddingValues = remember(navigationBarsHeight, imeHeight) {
        PaddingValues(
            bottom = max(navigationBarsHeight, imeHeight)
        )
    }

    Column(
        modifier = modifier,
    ) {
        Handle(
            modifier = Modifier
                .align(alignment = Alignment.CenterHorizontally)
                .padding(vertical = 16.dp),
        )
        Text(
            modifier = Modifier.padding(horizontal = 16.dp),
            style = MaterialTheme.bibLib.typography.base.caption,
            color = MaterialTheme.bibLib.colors.typography.light,
            text = title,
        )
        TextField(
            modifier = Modifier
                .focusRequester(focusRequester = focusRequester)
                .fillMaxWidth(),
            trailingIcon = {
                AnimatedVisibility(
                    visible = search.value.isNotBlank(),
                    enter = fadeIn(),
                    exit = fadeOut(),
                ) {
                    IconButton(
                        onClick = onClear,
                    ) {
                        Icon(
                            imageVector = Icons.Default.Clear,
                            tint = MaterialTheme.bibLib.colors.typography.emphasis,
                            contentDescription = null,
                        )
                    }
                }
            },
            value = search.value,
            singleLine = true,
            colors = TextFieldDefaults.outlinedTextFieldColors(),
            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
            keyboardActions = KeyboardActions(onDone = onIMEDone),
            onValueChange = onSearchUpdate
        )
        LazyColumn(
            modifier = Modifier.fillMaxSize(),
            contentPadding = paddingValues,
        ) {
            items(
                count = filters.itemCount,
                key = { filters[it]?.filterId ?: -1 },
            ) {
                val item = filters[it]
                Text(
                    modifier = Modifier
                        .clickable { item?.let(onFilter) }
                        .fillMaxWidth()
                        .padding(all = MaterialTheme.bibLib.dimen.thumbnail.padding),
                    style = MaterialTheme.typography.body1,
                    color = MaterialTheme.colors.onSurface,
                    text = item?.filterLabel ?: ""
                )
            }
        }
    }
}

@Composable
@Preview(showBackground = true, uiMode = UI_MODE_NIGHT_NO)
@Preview(showBackground = true, uiMode = UI_MODE_NIGHT_YES)
private fun FilterPageContentPreview() {
    BibLibTheme {
        FilterPageContent(
            focusRequester = remember { FocusRequester() },
            title = "Search by Author",
            search = remember { mutableStateOf("") },
            onSearchUpdate = { },
            onClear = { },
            filters = remember { emptyFlow<PagingData<FilterItemUio>>() }.collectAsLazyPagingItems(),
            onFilter = { },
            onIMEDone = { },
        )
    }
}