package com.aiosman.ravenow.ui.index.tabs.message.tab

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.rememberDebouncer
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.utils.NetworkUtils
import com.aiosman.ravenow.ui.network.NetworkErrorContentCompact

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun GroupChatListScreen() {
    val context = LocalContext.current
    val navController = LocalNavController.current
    val AppColors = LocalAppTheme.current

    val state = rememberPullRefreshState(
        refreshing = GroupChatListViewModel.refreshing,
        onRefresh = {
            GroupChatListViewModel.refreshPager(pullRefresh = true, context = context)
        }
    )

    LaunchedEffect(Unit) {
        GroupChatListViewModel.refreshPager(context = context)
    }


    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.background)
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .pullRefresh(state)
        ) {
            if (GroupChatListViewModel.groupChatList.isEmpty() && !GroupChatListViewModel.isLoading) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(horizontal = 16.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        modifier = Modifier.offset(y = (-40).dp)
                    ) {
                        val isNetworkAvailable = NetworkUtils.isNetworkAvailable(context)

                        if (isNetworkAvailable) {
                            Image(
                                painter = painterResource(id = R.mipmap.invalid_name_3),
                                contentDescription = "null data",
                                modifier = Modifier.size(120.dp)
                            )
                            Spacer(modifier = Modifier.height(12.dp))
                            Text(
                                text = stringResource(R.string.no_one_knocked_yet),
                                color = AppColors.text,
                                fontSize = 16.sp,
                                fontWeight = FontWeight.W600,
                                textAlign = TextAlign.Center,
                                modifier = Modifier.padding(horizontal = 24.dp),
                                maxLines = 2,
                                overflow = TextOverflow.Ellipsis
                            )
                        } else {
                            NetworkErrorContentCompact(
                                onReload = {
                                    GroupChatListViewModel.refreshPager(context = context)
                                }
                            )
                        }
                    }
                }
            } else {
                LazyColumn(
                    modifier = Modifier.fillMaxSize()
                ) {
                    itemsIndexed(
                        items = GroupChatListViewModel.groupChatList,
                        key = { _, item -> item.id }
                    ) { index, item ->
                        GroupChatItem(
                            conversation = item,
                            onGroupAvatarClick = { conv ->
                                GroupChatListViewModel.goToGroupDetail(conv, navController)
                            },
                            onChatClick = { conv ->
                                if (NetworkUtils.isNetworkAvailable(context)) {
                                    GroupChatListViewModel.goToChat(conv, navController)
                                } else {
                                    android.widget.Toast.makeText(context, "网络连接异常，请检查网络设置", android.widget.Toast.LENGTH_SHORT).show()
                                }
                            }
                        )

                        if (index < GroupChatListViewModel.groupChatList.size - 1) {
                            HorizontalDivider(
                                modifier = Modifier.padding(horizontal = 24.dp),
                                color = AppColors.divider
                            )
                        }
                    }

                    if (GroupChatListViewModel.isLoading && GroupChatListViewModel.groupChatList.isNotEmpty()) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(24.dp),
                                    color = AppColors.main
                                )
                            }
                        }
                    }
                }
            }

            PullRefreshIndicator(
                refreshing = GroupChatListViewModel.refreshing,
                state = state,
                modifier = Modifier.align(Alignment.TopCenter)
            )
        }

        GroupChatListViewModel.error?.let { error ->
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = error,
                    color = AppColors.error,
                    fontSize = 14.sp
                )
            }
        }
    }
}

@Composable
fun GroupChatItem(
    conversation: GroupConversation,
    onGroupAvatarClick: (GroupConversation) -> Unit = {},
    onChatClick: (GroupConversation) -> Unit = {}
) {
    val AppColors = LocalAppTheme.current
    val chatDebouncer = rememberDebouncer()
    val avatarDebouncer = rememberDebouncer()

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 24.dp, vertical = 12.dp)
            .noRippleClickable {
                chatDebouncer {
                    onChatClick(conversation)
                }
            }
    ) {
        Box {
            CustomAsyncImage(
                context = LocalContext.current,
                imageUrl = conversation.avatar,
                contentDescription = conversation.groupName,
                modifier = Modifier
                    .size(48.dp)
                    .clip(RoundedCornerShape(12.dp))
                    .noRippleClickable {
                        avatarDebouncer {
                            onGroupAvatarClick(conversation)
                        }
                    }
            )
        }

        Column(
            modifier = Modifier

                .weight(1f)
                .padding(start = 12.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = conversation.groupName,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = AppColors.text,
                    modifier = Modifier.weight(1f)
                )

                Spacer(modifier = Modifier.width(8.dp))

                Text(
                    text = conversation.lastMessageTime,
                    fontSize = 12.sp,
                    color = AppColors.secondaryText
                )
            }

            Spacer(modifier = Modifier.height(4.dp))

            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "${if (conversation.isSelf) stringResource(R.string.friend_chat_me_prefix) else ""}${conversation.displayText}",
                    fontSize = 14.sp,
                    color = AppColors.secondaryText,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    modifier = Modifier.weight(1f)
                )

                Spacer(modifier = Modifier.width(8.dp))

                if (conversation.unreadCount > 0) {
                    Box(
                        modifier = Modifier
                            .size(if (conversation.unreadCount > 99) 24.dp else 20.dp)
                            .background(
                                color = AppColors.main,
                                shape = CircleShape
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = if (conversation.unreadCount > 99) "99+" else conversation.unreadCount.toString(),
                            color = AppColors.mainText,
                            fontSize = if (conversation.unreadCount > 99) 9.sp else 10.sp,
                            fontWeight = FontWeight.Bold
                        )
                    }
                }
            }
        }
    }
}

