package com.iscs.bozzys.ui.pages.message

import android.content.Context
import android.content.Intent
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
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 androidx.lifecycle.viewmodel.compose.viewModel
import com.iscs.bozzys.R
import com.iscs.bozzys.api.Message
import com.iscs.bozzys.ui.common.Empty
import com.iscs.bozzys.ui.common.PageBase
import com.iscs.bozzys.ui.dialog.TipsDialog
import com.iscs.bozzys.ui.pages.compose.CardBox
import com.iscs.bozzys.ui.pages.vm.StatePageMessage
import com.iscs.bozzys.ui.pages.vm.VMMessage
import com.iscs.bozzys.ui.theme.Text
import com.iscs.bozzys.utils.DateUtil.getShowDate
import com.iscs.bozzys.utils.DateUtil.getShowDateOrTime

/**
 * 打开消息中心页面
 */
fun Context.openPageMessage() {
    startActivity(Intent(this, PageMessage::class.java))
}

/**
 * 消息中心
 */
class PageMessage : PageBase() {
    @Composable
    override fun GetViews(pv: PaddingValues) {
        val vm: VMMessage = viewModel()
        val state by vm.state.collectAsState()
        LaunchedEffect(Unit) {
            vm.toast.initToast()
            vm.loading.initLoading()
            vm.init()
        }
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(MaterialTheme.colorScheme.background)
        ) {
            // 顶部工具栏
            Column(
                modifier = Modifier
                    .padding(bottom = pv.calculateBottomPadding())
                    .fillMaxSize()
            ) {
                TopToolBar(pv, vm)
                MessageList(vm)
            }
            // 提示弹窗
            TipsDialog(
                show = state.tips.show, title = state.tips.title, content = state.tips.content,
                onCancel = { vm.hideTips() },
                onConfirm = { vm.onTipsConfirm() })
        }
    }


    /**
     * 顶部工具栏
     */
    @Composable
    private fun TopToolBar(pv: PaddingValues, vm: VMMessage) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .background(brush = Brush.horizontalGradient(listOf(Color(0xFFFF8C00), Color(0xFFFFA500))))
                .padding(top = pv.calculateTopPadding())
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(66.dp)
                    .padding(horizontal = 10.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(
                    Modifier
                        .width(80.dp)
                        .padding(start = 6.dp)
                ) {
                    Icon(
                        painter = painterResource(R.drawable.back),
                        contentDescription = "",
                        modifier = Modifier
                            .size(32.dp)
                            .clip(RoundedCornerShape(50))
                            .background(Color(0xFFFFA126))
                            .clickable(onClick = { destroy() })
                            .padding(8.dp),
                        tint = Color.White
                    )
                }
                Text(
                    "消息中心",
                    fontSize = 18.sp,
                    color = Color.White,
                    fontWeight = FontWeight.Medium,
                    modifier = Modifier.weight(1f),
                    textAlign = TextAlign.Center
                )
                Row(Modifier.width(80.dp)) {
                    Spacer(modifier = Modifier.weight(1f))
                    Icon(
                        painter = painterResource(R.drawable.read_all),
                        contentDescription = null,
                        modifier = Modifier
                            .size(36.dp)
                            .clip(RoundedCornerShape(6.dp))
                            .clickable(onClick = { vm.onReadAll() })
                            .padding(8.dp),
                        tint = Color.White
                    )
                    // 后端暂不支持删除消息
//                    Icon(
//                        painter = painterResource(R.drawable.delete_all),
//                        contentDescription = null,
//                        modifier = Modifier
//                            .size(36.dp)
//                            .clip(RoundedCornerShape(6.dp))
//                            .clickable(onClick = { vm.onDeleteAll() })
//                            .padding(9.dp),
//                        tint = Color.White
//                    )
                }
            }
        }
    }

}

/**
 * 消息列表
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun MessageList(vm: VMMessage) {
    val state by vm.state.collectAsState()
    // 监听顶部Item
    val listState = rememberLazyListState()
    // 当前顶部Item
    val topIdx by remember {
        derivedStateOf {
            listState.firstVisibleItemIndex
        }
    }
    // 监听列表是否滑动到底部
    val shouldLoadMore by remember {
        derivedStateOf {
            val layoutInfo = listState.layoutInfo
            val totalItems = layoutInfo.totalItemsCount
            val lastVisibleItemIndex = layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0
            lastVisibleItemIndex >= totalItems - 2
        }
    }
    // 处理加载更多数据
    LaunchedEffect(shouldLoadMore) {
        if (shouldLoadMore && state.messages.isNotEmpty() && !state.page.noMore) {
            vm.getMessage(state.page.copy(page = state.page.page + 1, isRefresh = false))
        }
    }
    PullToRefreshBox(state.page.isRefresh, onRefresh = {
        vm.getMessage(StatePageMessage(isRefresh = true, page = 1))
    }, modifier = Modifier.fillMaxSize()) {
        Box(
            modifier = Modifier
                .padding(top = 5.dp)
                .fillMaxSize()
        ) {
            LazyColumn(
                state = listState,
                modifier = Modifier.fillMaxSize()
            ) {
                items(state.messages) { item ->
                    if (item.uiIsTitle) {
                        MessageListItemTitle(item)
                    } else {
                        MessageListItemContent(vm, item)
                    }
                }
                // 数据不为空才会显示加载中
                if (state.messages.isNotEmpty()) item {
                    Text(
                        if (state.page.noMore) "没有更多数据" else "加载更多数据中...",
                        fontSize = 12.sp,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(bottom = 10.dp),
                        textAlign = TextAlign.Center,
                        color = Text.copy(alpha = 0.6f)
                    )
                }
            }
            if (state.messages.isEmpty()) Empty(tips = "暂无消息")
            // 悬浮在列表的顶部
            if (state.messages.isNotEmpty()) Box(
                Modifier.background(MaterialTheme.colorScheme.background),
                contentAlignment = Alignment.CenterStart
            ) {
                MessageListItemTitle(state.messages[topIdx])
            }
        }
    }
}

/**
 * 消息标题
 */
@Composable
private fun MessageListItemTitle(message: Message) {
    Text(
        message.createTime.getShowDate(),
        fontSize = 16.sp,
        lineHeight = 26.sp,
        fontWeight = FontWeight.Medium,
        color = Text,
        modifier = Modifier
            .fillMaxWidth()
            .height(26.dp)
            .padding(horizontal = 16.dp),
    )
}

/**
 * 消息内容
 */
@Composable
private fun MessageListItemContent(vm: VMMessage, msg: Message) {
    CardBox(modifier = Modifier.padding(vertical = 8.dp, horizontal = 16.dp)) {
        Row(
            Modifier
                .fillMaxWidth()
                .height(122.dp)
                .clickable(onClick = { vm.onMessage(msg) })
                .padding(16.dp)
        ) {
            Icon(
                painterResource(R.drawable.bell), contentDescription = null,
                modifier = Modifier
                    .size(40.dp)
                    .clip(RoundedCornerShape(50))
                    .background(MaterialTheme.colorScheme.primary)
                    .padding(8.dp),
                tint = Color.White
            )
            Column(
                Modifier
                    .padding(start = 15.dp, end = 10.dp)
                    .fillMaxHeight()
                    .weight(1f)
            ) {
                Text(msg.title ?: "提醒", fontSize = 15.sp, fontWeight = FontWeight.Medium, color = Text)
                Text(
                    msg.templateContent,
                    fontSize = 13.sp,
                    color = Color(0xFF666666),
                    overflow = TextOverflow.Ellipsis,
                    maxLines = 2,
                    modifier = Modifier.fillMaxWidth()
                )
                Spacer(Modifier.weight(1f))
                Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
                    Text(msg.createTime.getShowDateOrTime(), fontSize = 12.sp, color = Color(0xFF999999))
                    Spacer(Modifier.weight(1f))
                    Text("作业管理", fontSize = 13.sp, color = Color(0xFF999999))
                }
            }
            Spacer(
                Modifier
                    .size(8.dp)
                    .clip(RoundedCornerShape(50))
                    .background(if (msg.readStatus) Color.Transparent else Color(0xFFFF4500))
                    .align(Alignment.CenterVertically)
            )
        }
    }
}