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

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
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.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
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.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
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.Button
import androidx.compose.material.ButtonDefaults
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.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.DisposableEffect
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.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
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.text.style.TextAlign
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.AppState
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.entity.AccountProfileEntity
import com.aiosman.ravenow.GuestLoginCheckOut
import com.aiosman.ravenow.GuestLoginCheckOutScene
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.MomentCard
import com.aiosman.ravenow.ui.composables.TabItem
import com.aiosman.ravenow.ui.composables.TabSpacer
import com.aiosman.ravenow.ui.composables.rememberDebouncer
import com.aiosman.ravenow.ui.index.tabs.message.tab.AgentChatListViewModel
import com.aiosman.ravenow.ui.index.tabs.profile.composable.RoomItem
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.navigateToGroupChat
import com.aiosman.ravenow.ui.NavigationRoute
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import kotlinx.coroutines.launch
import com.aiosman.ravenow.utils.NetworkUtils
import com.aiosman.ravenow.ui.network.NetworkErrorContentInline


@OptIn(ExperimentalFoundationApi::class)
@Preview
@Composable
fun SearchScreen() {
    val AppColors = LocalAppTheme.current
    val context = LocalContext.current
    val model = SearchViewModel
    val coroutineScope = rememberCoroutineScope()
    val pagerState = rememberPagerState(pageCount = { 4 })
    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 = !AppState.darkMode)
    }
    LaunchedEffect(Unit) {
        model.ensureInit(context)
        if (model.requestFocus) {
            focusRequester.requestFocus()
            model.requestFocus = false
        }
    }
    DisposableEffect(Unit) {
        onDispose {
            // 离开页面时重置搜索状态与文本
            model.searchText = ""
            model.ResetModel()
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.background)
            .padding(bottom = navigationBarPaddings)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .background(
                    AppColors.background
                )
                .padding(bottom = 10.dp)
        ) {
            Spacer(modifier = Modifier.height(statusBarPaddingValues.calculateTopPadding()))
            Row(
                modifier = Modifier.padding(top = 16.dp, start = 16.dp, end = 16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                SearchInput(
                    modifier = Modifier
                        .weight(1f),
                    text = model.searchText,
                    onTextChange = {
                        model.onTextChanged(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 {
                        // 退出时也重置，确保返回后显示历史而不是上次结果
                        model.searchText = ""
                        model.ResetModel()
                        navController.navigateUp()
                    },
                    color = AppColors.text
                )
            }

            // 历史搜索（当不展示结果时）
            if (!model.showResult) {
                HistorySection(
                    onClear = { model.clearHistory() },
                    onClick = { term ->
                        coroutineScope.launch {
                            keyboardController?.hide()
                            model.searchText = term
                            model.onTextChanged(term)
                            pagerState.animateScrollToPage(0)
                            model.search()
                        }
                    },
                    onRemove = { term -> model.removeHistoryItem(term) }
                )
            }

            // 添加user、dynamic和ai标签页
            if (model.showResult) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .wrapContentHeight()
                        .padding(start = 16.dp, top = 16.dp),
                    horizontalArrangement = Arrangement.Start,
                    verticalAlignment = Alignment.Bottom
                ) {
                    Box {
                        TabItem(
                            text = stringResource(R.string.moment),
                            isSelected = pagerState.currentPage == 0,
                            onClick = {
                                coroutineScope.launch {
                                    pagerState.animateScrollToPage(0)
                                }
                            }
                        )
                    }
                    TabSpacer()
                    Box {
                        TabItem(
                            text = stringResource(R.string.users),
                            isSelected = pagerState.currentPage == 1,
                            onClick = {
                                coroutineScope.launch {
                                    pagerState.animateScrollToPage(1)
                                }
                            }
                        )
                    }
                    TabSpacer()
                    Box {
                        TabItem(
                            text = stringResource(R.string.chat_ai),
                            isSelected = pagerState.currentPage == 2,
                            onClick = {
                                coroutineScope.launch {
                                    pagerState.animateScrollToPage(2)
                                }
                            }
                        )
                    }
                    TabSpacer()
                    Box {
                        TabItem(
                            text = stringResource(R.string.chat_group),
                            isSelected = pagerState.currentPage == 3,
                            onClick = {
                                coroutineScope.launch {
                                    pagerState.animateScrollToPage(3)
                                }
                            }
                        )
                    }
                }
            }
        }

        if (model.showResult) {
            SearchPager(
                pagerState = pagerState
            )
        }
    }
}

@OptIn(ExperimentalLayoutApi::class, ExperimentalFoundationApi::class)
@Composable
fun HistorySection(
    onClear: () -> Unit,
    onClick: (String) -> Unit,
    onRemove: (String) -> Unit
) {
    val AppColors = LocalAppTheme.current
    val model = SearchViewModel
    val items = model.historyFlow.collectAsState(initial = emptyList()).value
    if (items.isEmpty()) return
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 12.dp)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = stringResource(R.string.recent_search),
                color = AppColors.text,
                fontSize = 16.sp,
                fontWeight = FontWeight.W600
            )
            Spacer(modifier = Modifier.weight(1f))
            Text(
                text = stringResource(R.string.clear),
                color = AppColors.secondaryText,
                fontSize = 14.sp,
                modifier = Modifier.noRippleClickable { onClear() }
            )
        }
        Spacer(modifier = Modifier.height(12.dp))
        FlowRow(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            items.forEach { term ->
                Box(
                    modifier = Modifier
                        .background(AppColors.inputBackground, RoundedCornerShape(16.dp))
                        .combinedClickable(
                            onClick = { onClick(term) },
                            onLongClick = { onRemove(term) }
                        )
                        .padding(horizontal = 12.dp, vertical = 8.dp)
                ) {
                    Text(
                        text = term,
                        color = AppColors.text,
                        fontSize = 14.sp
                    )
                }
            }
        }
    }
}

@Composable
fun SearchInput(
    modifier: Modifier = Modifier,
    text: String = "",
    onTextChange: (String) -> Unit = {},
    onSearch: () -> Unit = {},
    focusRequester: FocusRequester = remember { FocusRequester() }
) {
    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)
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                Icons.Default.Search,
                contentDescription = null,
                tint = AppColors.inputHint
            )
            Box {
                if (text.isEmpty()) {
                    Text(
                        text = context.getString(R.string.search),
                        modifier = Modifier.padding(start = 8.dp),
                        color = AppColors.inputHint,
                        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,
                        color = AppColors.text
                    ),
                    keyboardOptions = KeyboardOptions.Default.copy(
                        imeAction = ImeAction.Search
                    ),
                    keyboardActions = KeyboardActions(
                        onSearch = {
                            onSearch()
                        }
                    ),
                    cursorBrush = SolidColor(AppColors.text)
                )
            }
        }


    }
}

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

        ) { page ->
        when (page) {
            0 -> MomentResultTab()
            1 -> UserResultTab()
            2 -> AiResultTab()
            3 -> RoomResultTab()
        }
    }
}

@Composable
fun MomentResultTab() {
    val model = SearchViewModel
    var dataFlow = model.momentsFlow
    var moments = dataFlow.collectAsLazyPagingItems()
    val AppColors = LocalAppTheme.current
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    val navController = LocalNavController.current
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.background)
    ) {
        if (moments.itemCount == 0 && model.showResult) {
            val isNetworkAvailable = NetworkUtils.isNetworkAvailable(context)
            SearchPlaceholderContent(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                isNetworkAvailable = isNetworkAvailable,
                onReload = {
                    SearchViewModel.ResetModel()
                    SearchViewModel.search()
                }
            )
        } else {
            LazyColumn(
                modifier = Modifier.fillMaxSize(),
            ) {
                items(moments.itemCount) { idx ->
                    val momentItem = moments[idx] ?: return@items
                    
                    val commentDebouncer = rememberDebouncer()
                    val likeDebouncer = rememberDebouncer()
                    val favoriteDebouncer = rememberDebouncer()
                    val followDebouncer = rememberDebouncer()
                    
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .background(Color.White)
                    ) {
                        MomentCard(
                            momentEntity = momentItem,
                            onAddComment = {
                                commentDebouncer {
                                    // 检查游客模式，如果是游客则跳转登录
                                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.COMMENT_MOMENT)) {
                                        navController.navigate(NavigationRoute.Login.route)
                                    } else {
                                        scope.launch {
                                            model.onAddComment(momentItem.id)
                                        }
                                    }
                                }
                            },
                            onLikeClick = {
                                likeDebouncer {
                                    // 检查游客模式，如果是游客则跳转登录
                                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                                        navController.navigate(NavigationRoute.Login.route)
                                    } else {
                                        scope.launch {
                                            if (momentItem.liked) {
                                                model.dislikeMoment(momentItem.id)
                                            } else {
                                                model.likeMoment(momentItem.id)
                                            }
                                        }
                                    }
                                }
                            },
                            onFavoriteClick = {
                                favoriteDebouncer {
                                    // 检查游客模式，如果是游客则跳转登录
                                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                                        navController.navigate(NavigationRoute.Login.route)
                                    } else {
                                        scope.launch {
                                            if (momentItem.isFavorite) {
                                                model.unfavoriteMoment(momentItem.id)
                                            } else {
                                                model.favoriteMoment(momentItem.id)
                                            }
                                        }
                                    }
                                }
                            },
                            onFollowClick = {
                                followDebouncer {
                                    // 检查游客模式，如果是游客则跳转登录
                                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.FOLLOW_USER)) {
                                        navController.navigate(NavigationRoute.Login.route)
                                    } else {
                                        model.momentFollowAction(momentItem)
                                    }
                                }
                            },
                            showFollowButton = true
                        )
                    }
//                Spacer(modifier = Modifier.padding(16.dp))
                }
            }
        }
    }
}

@Composable
fun UserResultTab() {
    val model = SearchViewModel
    val users = model.usersFlow.collectAsLazyPagingItems()
    val scope = rememberCoroutineScope()
    val context = LocalContext.current
    Box(
        modifier = Modifier.fillMaxSize()
    ) {
        if (users.itemCount == 0 && model.showResult) {
            val isNetworkAvailable = NetworkUtils.isNetworkAvailable(context)
            SearchPlaceholderContent(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                isNetworkAvailable = isNetworkAvailable,
                onReload = {
                    SearchViewModel.ResetModel()
                    SearchViewModel.search()
                }
            )
        } else {
            LazyColumn(
                modifier = Modifier.fillMaxSize(),
            ) {
                items(users.itemCount) { idx ->
                    val userItem = users[idx] ?: return@items
                    UserItem(userItem) {
                        scope.launch {
                            if (userItem.isFollowing) {
                                model.unfollowUser(userItem.id)
                            } else {
                                model.followUser(userItem.id)
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun UserItem(
    accountProfile: AccountProfileEntity,
    onFollow: (AccountProfileEntity) -> Unit = {},
) {
    val context = LocalContext.current
    val navController = LocalNavController.current
    val AppColors = LocalAppTheme.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(48.dp)
                .clip(CircleShape),
            contentDescription = null
        )
        Spacer(modifier = Modifier.padding(8.dp))
        Row(
            modifier = Modifier.fillMaxWidth()
        ) {
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = accountProfile.nickName,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = AppColors.text
                )
                Spacer(modifier = Modifier.width(2.dp))
                Text(
                    text = stringResource(
                        R.string.search_user_item_follower_count,
                        accountProfile.followerCount
                    ), fontSize = 14.sp, color = AppColors.secondaryText
                )
            }
            Spacer(modifier = Modifier.width(16.dp))
//            Box {
//                if (accountProfile.id != AppState.UserId) {
//                    if (accountProfile.isFollowing) {
//                        ActionButton(
//                            text = stringResource(R.string.following_upper),
//                            backgroundColor = Color(0xFF9E9E9E),
//                            contentPadding = PaddingValues(vertical = 4.dp, horizontal = 8.dp),
//                            color = Color.White,
//                            fullWidth = false
//                        ) {
//                            onFollow(accountProfile)
//                        }
//                    } else {
//                        ActionButton(
//                            text = stringResource(R.string.follow_upper),
//                            backgroundColor = Color(0xffda3832),
//                            contentPadding = PaddingValues(vertical = 4.dp, horizontal = 8.dp),
//                            color = Color.White,
//                            fullWidth = false
//                        ) {
//                            onFollow(accountProfile)
//                        }
//                    }
//                }
//            }
        }
    }
}
@Composable
fun AiResultTab() {
    val AppColors = LocalAppTheme.current
    val context = LocalContext.current
    val model = SearchViewModel
    val agents = model.agentsFlow.collectAsLazyPagingItems()
    val navController = LocalNavController.current
    val scope = rememberCoroutineScope()
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.background)
    ) {
        if (agents.itemCount == 0 && model.showResult) {
            val isNetworkAvailable = NetworkUtils.isNetworkAvailable(context)
            SearchPlaceholderContent(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                isNetworkAvailable = isNetworkAvailable,
                onReload = {
                    SearchViewModel.ResetModel()
                    SearchViewModel.search()
                }
            )
        } else {
            LazyColumn(
                modifier = Modifier.fillMaxSize(),
            ) {
                items(agents.itemCount) { idx ->
                    val agent = agents[idx] ?: return@items
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp)
                            .noRippleClickable {
                                scope.launch {
                                    try {
                                        val userService = com.aiosman.ravenow.data.UserServiceImpl()
                                        val profile = userService.getUserProfileByOpenId(agent.openId)
                                        navController.navigate(
                                            NavigationRoute.AccountProfile.route
                                                .replace("{id}", profile.id.toString())
                                                .replace("{isAiAccount}", "true")
                                        )
                                    } catch (e: Exception) {
                                        // 处理错误
                                        e.printStackTrace()
                                    }
                                }
                            },
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        CustomAsyncImage(
                            context,
                            imageUrl = agent.avatar,
                            modifier = Modifier
                                .size(48.dp)
                                .clip(RoundedCornerShape(24.dp)),
                            contentDescription = null
                        )
                        Spacer(modifier = Modifier.width(12.dp))
                        Column(modifier = Modifier.weight(1f)) {
                            Text(
                                text = agent.title,
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Bold,
                                color = AppColors.text
                            )
                            Spacer(modifier = Modifier.height(4.dp))
                            Text(
                                text = agent.desc,
                                fontSize = 14.sp,
                                color = AppColors.secondaryText,
                                maxLines = 1
                            )
                        }
                    }
                }
            }
        }
    }
}
@Composable
fun RoomResultTab() {
    val model = SearchViewModel
    val rooms = model.roomsFlow.collectAsLazyPagingItems()
    val AppColors = LocalAppTheme.current
    val context = LocalContext.current
    val navController = LocalNavController.current
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.background)
    ) {
        if (rooms.itemCount == 0 && model.showResult) {
            val isNetworkAvailable = NetworkUtils.isNetworkAvailable(context)
            SearchPlaceholderContent(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                isNetworkAvailable = isNetworkAvailable,
                onReload = {
                    SearchViewModel.ResetModel()
                    SearchViewModel.search()
                }
            )
        } else {
            LazyColumn(
                modifier = Modifier.fillMaxSize(),
            ) {
                items(rooms.itemCount) { idx ->
                    val roomItem = rooms[idx] ?: return@items
                    RoomItem(
                        room = roomItem,
                        onRoomClick = { roomEntity ->
                            navController.navigateToGroupChat(
                                id = roomEntity.trtcRoomId,
                                name = roomEntity.name,
                                avatar = roomEntity.avatar
                            )
                        }
                    )
                }
            }
        }
    }
}

@Composable
fun SearchPlaceholderContent(
    modifier: Modifier = Modifier,
    isNetworkAvailable: Boolean,
    onReload: () -> Unit
) {
    val appColors = LocalAppTheme.current
    Column(
        modifier = modifier,
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        if (isNetworkAvailable) {
            androidx.compose.foundation.Image(
                painter = painterResource(id = R.mipmap.empty_img),
                contentDescription = "No Comment",
                modifier = Modifier.size(168.dp)
            )
            Text(
                text = stringResource(R.string.null_search),
                color = appColors.text,
                fontSize = 16.sp,
                fontWeight = FontWeight.W600
            )
        } else {
            NetworkErrorContentInline(onReload = onReload)
        }
    }
}

