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

import androidx.compose.foundation.ExperimentalFoundationApi
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.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Icon
import androidx.compose.material.Tab
import androidx.compose.material.TabRow
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
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.sp
import androidx.paging.compose.collectAsLazyPagingItems
import com.aiosman.riderpro.LocalNavController
import com.aiosman.riderpro.R
import com.aiosman.riderpro.entity.AccountProfileEntity
import com.aiosman.riderpro.ui.composables.CustomAsyncImage
import com.aiosman.riderpro.ui.index.tabs.moment.MomentCard
import com.aiosman.riderpro.ui.modifiers.noRippleClickable
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import kotlinx.coroutines.launch


@OptIn(ExperimentalFoundationApi::class)
@Preview
@Composable
fun SearchScreen() {
    val context = LocalContext.current
    val model = SearchViewModel
    val categories = listOf(context.getString(R.string.moment), context.getString(R.string.users))
    val coroutineScope = rememberCoroutineScope()
    val pagerState = rememberPagerState(pageCount = { categories.size })
    val selectedTabIndex = remember { derivedStateOf { pagerState.currentPage } }
    val keyboardController = LocalSoftwareKeyboardController.current
    val systemUiController = rememberSystemUiController()
    val statusBarPaddingValues = WindowInsets.systemBars.asPaddingValues()
    val navigationBarPaddings =
        WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()
    val focusRequester = remember { FocusRequester() }
    val navController = LocalNavController.current
    LaunchedEffect(Unit) {
        systemUiController.setStatusBarColor(Color.Transparent, darkIcons = true)
    }
    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0xFFF0F2F5))
            .padding(bottom = navigationBarPaddings)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .background(Color.White)
                .padding(bottom = 10.dp)
        ) {
            Spacer(modifier = Modifier.height(statusBarPaddingValues.calculateTopPadding()))
            Row(
                modifier = Modifier.padding(top = 16.dp, start = 24.dp, end = 24.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                SearchInput(
                    modifier = Modifier
                        .weight(1f),
                    text = model.searchText,
                    onTextChange = {
                        model.searchText = it
                    },
                    onSearch = {
                        model.search()
                        // hide ime
                        keyboardController?.hide() // Hide the keyboard
                    },
                    focusRequester = focusRequester
                )
                Spacer(modifier = Modifier.size(16.dp))
                Text(
                    stringResource(R.string.cancel),
                    fontSize = 16.sp,
                    modifier = Modifier.noRippleClickable {
                        navController.popBackStack()
                    })
            }

        }

        if (model.showResult) {
            TabRow(
                selectedTabIndex = selectedTabIndex.value,
                backgroundColor = Color.White,
            ) {
                categories.forEachIndexed { index, category ->
                    Tab(
                        selected = selectedTabIndex.value == index,
                        onClick = {
                            coroutineScope.launch {
                                pagerState.animateScrollToPage(index)
                            }
                        },
                        text = { Text(category) }
                    )
                }
            }
            SearchPager(
                pagerState = pagerState
            )
        }
    }
}

@Composable
fun SearchInput(
    modifier: Modifier = Modifier,
    text: String = "",
    onTextChange: (String) -> Unit = {},
    onSearch: () -> Unit = {},
    focusRequester: FocusRequester = remember { FocusRequester() }
) {
    val context = LocalContext.current
    Box(
        modifier = modifier
            .clip(shape = RoundedCornerShape(16.dp))
            .background(Color(0xFFF4F5F6))
            .padding(horizontal = 16.dp, vertical = 12.dp)
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                Icons.Default.Search,
                contentDescription = null,
                tint = Color(0xFF9E9E9E)
            )
            Box {
                if (text.isEmpty()) {
                    Text(
                        text = context.getString(R.string.search),
                        modifier = Modifier.padding(start = 8.dp),
                        color = Color(0xFF9E9E9E),
                        fontSize = 18.sp
                    )
                }
                BasicTextField(
                    value = text,
                    onValueChange = {
                        onTextChange(it)
                    },
                    modifier = Modifier
                        .padding(start = 8.dp)
                        .fillMaxWidth()
                        .focusRequester(focusRequester),
                    singleLine = true,
                    textStyle = TextStyle(
                        fontSize = 18.sp
                    ),
                    keyboardOptions = KeyboardOptions.Default.copy(
                        imeAction = ImeAction.Search
                    ),
                    keyboardActions = KeyboardActions(
                        onSearch = {
                            onSearch()
                        }
                    )
                )
            }
        }


    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun SearchPager(
    pagerState: PagerState,
) {
    HorizontalPager(
        state = pagerState,
        modifier = Modifier.fillMaxSize(),

        ) { page ->
        when (page) {
            0 -> MomentResultTab()
            1 -> UserResultTab()
        }
    }
}

@Composable
fun MomentResultTab() {
    val model = SearchViewModel
    var dataFlow = model.momentsFlow
    var moments = dataFlow.collectAsLazyPagingItems()
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0xFFF0F2F5))
    ) {
        LazyColumn(
            modifier = Modifier.fillMaxSize(),
        ) {
            items(moments.itemCount) { idx ->
                val momentItem = moments[idx] ?: return@items
                Box(
                    modifier = Modifier
                        .fillMaxWidth().background(Color.White)
                ) {
                    MomentCard(momentEntity = momentItem, hideAction = true)
                }
                Spacer(modifier = Modifier.padding(16.dp))
            }
        }
    }
}

@Composable
fun UserResultTab() {
    val model = SearchViewModel
    val users = model.usersFlow.collectAsLazyPagingItems()
    Box(
        modifier = Modifier.fillMaxSize()
    ) {
        LazyColumn(
            modifier = Modifier.fillMaxSize(),
        ) {
            items(users.itemCount) { idx ->
                val userItem = users[idx] ?: return@items
                UserItem(userItem)
            }
        }
    }
}

@Composable
fun UserItem(accountProfile: AccountProfileEntity) {
    val context = LocalContext.current
    val navController = LocalNavController.current
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp)
            .noRippleClickable {
                navController.navigate("AccountProfile/${accountProfile.id}")
            },
        verticalAlignment = Alignment.CenterVertically
    ) {
        CustomAsyncImage(
            context,
            imageUrl = accountProfile.avatar,
            modifier = Modifier
                .size(64.dp)
                .clip(CircleShape),
            contentDescription = null
        )
        Spacer(modifier = Modifier.padding(16.dp))
        Text(text = accountProfile.nickName, fontSize = 18.sp, fontWeight = FontWeight.Bold)
    }
}