package com.aiosman.ravenow.ui.index.tabs.search

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.paging.compose.collectAsLazyPagingItems
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.StatusBarSpacer
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.navigateToPost


@OptIn( ExperimentalMaterialApi::class)
@Preview
@Composable
fun DiscoverScreen() {
    val model = DiscoverViewModel
    val AppColors = LocalAppTheme.current
    val navController = LocalNavController.current
    val navigationBarPaddings =
        WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding() + 48.dp
    LaunchedEffect(Unit) {
        DiscoverViewModel.refreshPager()
    }
    var refreshing by remember { mutableStateOf(false) }
    val state = rememberPullRefreshState(refreshing, onRefresh = {
        model.refreshPager()
    })

    Column(
        modifier = Modifier
            .fillMaxSize()
            .pullRefresh(state)
            .padding(bottom = navigationBarPaddings)
    ) {
        Column(
            modifier = Modifier.fillMaxWidth().background(
                AppColors.background).padding(bottom = 10.dp)
        ) {
            StatusBarSpacer()
            SearchButton(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp, start = 16.dp, end = 16.dp),
            ) {
                SearchViewModel.requestFocus = true
                navController.navigate(NavigationRoute.Search.route)
            }
        }

        Box(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
        ) {
            DiscoverView()
            PullRefreshIndicator(refreshing, state, Modifier.align(Alignment.TopCenter))
        }
    }
}

@Composable
fun SearchButton(
    modifier: Modifier = Modifier,
    clickAction: () -> Unit = {}
) {
    val AppColors = LocalAppTheme.current
    val context = LocalContext.current
    Box(
        modifier = modifier
            .clip(shape = RoundedCornerShape(8.dp))
            .background(
                AppColors.inputBackground)
            .padding(horizontal = 16.dp, vertical = 12.dp)
            .noRippleClickable {
                clickAction()
            }
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                Icons.Default.Search,
                contentDescription = null,
                tint = AppColors.inputHint
            )
            Box {
                Text(
                    text = context.getString(R.string.search),
                    modifier = Modifier.padding(start = 8.dp),
                    color = AppColors.inputHint,
                    fontSize = 18.sp
                )
            }
        }
    }
}

@Composable
fun DiscoverView() {
    val model = DiscoverViewModel
    var dataFlow = model.discoverMomentsFlow
    var moments = dataFlow.collectAsLazyPagingItems()
    val context = LocalContext.current
    val navController = LocalNavController.current
    LazyVerticalGrid(
        columns = GridCells.Fixed(3),
        modifier = Modifier.fillMaxSize().padding(bottom = 8.dp),
//        contentPadding = PaddingValues(8.dp)
    ) {
        items(moments.itemCount) { idx ->
            val momentItem = moments[idx] ?: return@items
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(1f)
                    .padding(2.dp)
                    .clip(RoundedCornerShape(8.dp))
                    .noRippleClickable {
                        navController.navigateToPost(
                            id = momentItem.id,
                            highlightCommentId = 0,
                            initImagePagerIndex = 0
                        )
                    }
            ) {
                CustomAsyncImage(
                    imageUrl = momentItem.images[0].thumbnail,
                    contentDescription = "",
                    modifier = Modifier
                        .fillMaxSize(),
                    context = context
                )
                if (momentItem.images.size > 1) {
                    Box(
                        modifier = Modifier
                            .padding(top = 8.dp, end = 8.dp)
                            .align(Alignment.TopEnd)
                    ) {
                        Image(
                            modifier = Modifier.size(24.dp),
                            painter = painterResource(R.drawable.rider_pro_picture_more),
                            contentDescription = "",
                        )
                    }
                }


            }

        }
    }
}