package com.iscs.bozzys.ui.pages.return_device

import android.content.Context
import android.content.Intent
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.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.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
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.ui.common.PageBase
import com.iscs.bozzys.ui.dialog.ExceptReportDialog
import com.iscs.bozzys.ui.pages.compose.CardBox
import com.iscs.bozzys.ui.pages.vm.VMReturnDevice
import com.iscs.bozzys.ui.theme.Text

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

/**
 * 归还设备
 */
class PageReturnDevice : PageBase() {
    @Composable
    override fun GetViews(pv: PaddingValues) {
        val vm: VMReturnDevice = 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)
                DeviceList(vm)
            }
            // 异常上报Dialog
            ExceptReportDialog(state.showExceptDialog, state.exceptDeviceMac,{
                vm.hideExceptDialog()
                vm.reportExcept()
            }, { vm.hideExceptDialog() })
        }
    }


    /**
     * 顶部工具栏
     */
    @Composable
    private fun TopToolBar(pv: PaddingValues, vm: VMReturnDevice) {
        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)) {

                }
            }
        }
    }

}

/**
 * 消息列表
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun DeviceList(vm: VMReturnDevice) {
    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(3) { item -> DeviceItem(item, vm) }
            // 数据不为空才会显示加载中
//                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)
//                    )
//                }
        }
//            Empty(tips = "暂无待归还设备")
//            // 悬浮在列表的顶部
//            if (state.messages.isNotEmpty()) Box(
//                Modifier.background(MaterialTheme.colorScheme.background),
//                contentAlignment = Alignment.CenterStart
//            ) {
//                MessageListItemTitle(state.messages[topIdx])
//            }
//        }
    }
}

/**
 * 消息内容
 */
@Composable
private fun DeviceItem(item: Int, vm: VMReturnDevice) {
    CardBox(modifier = Modifier.padding(vertical = 8.dp, horizontal = 16.dp)) {
        Row(
            Modifier
                .fillMaxWidth()
                .height(100.dp)
                .clickable(onClick = { })
                .padding(horizontal = 16.dp),
            horizontalArrangement = Arrangement.Center,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                painterResource(if (item == 1) R.drawable.key else R.drawable.lock),
                contentDescription = null,
                modifier = Modifier
                    .size(40.dp)
                    .clip(RoundedCornerShape(50))
                    .background(MaterialTheme.colorScheme.primary)
                    .padding(8.dp),
                tint = Color.White
            )
            Column(
                modifier = Modifier
                    .padding(horizontal = 10.dp)
                    .weight(1f)
            ) {
                Text(
                    if (item == 1) "钥匙" else "挂锁",
                    fontSize = 16.sp,
                    lineHeight = 16.sp,
                    fontWeight = FontWeight.Medium,
                    color = Text
                )
                Text(
                    "32A9553$item",
                    fontSize = 13.sp,
                    lineHeight = 13.sp,
                    color = Color(0xFF666666),
                    overflow = TextOverflow.Ellipsis,
                    maxLines = 2,
                    modifier = Modifier.fillMaxWidth()
                )
                Text(
                    "领取时间：2026-03-12 13:59:39",
                    fontSize = 12.sp,
                    color = Color(0xFF999999)
                )
            }
            Button(
                { vm.showExceptDialog("32A9553$item") },
                shape = RoundedCornerShape(6.dp),
                contentPadding = PaddingValues(vertical = 0.dp, horizontal = 5.dp),
                modifier = Modifier.height(28.dp)
            ) {
                Text("上报异常", fontSize = 13.sp)
            }
        }
    }
}