package com.iscs.bozzys.ui.pages.home

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
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.defaultMinSize
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.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
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.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
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.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
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.compose.ui.zIndex
import coil.compose.AsyncImage
import com.iscs.bozzys.R
import com.iscs.bozzys.api.Message
import com.iscs.bozzys.ui.pages.compose.CardBox
import com.iscs.bozzys.ui.pages.compose.TaskListItem
import com.iscs.bozzys.ui.pages.message.openPageMessage
import com.iscs.bozzys.ui.pages.return_device.openPageReturnDevice
import com.iscs.bozzys.ui.pages.vm.VMHome
import com.iscs.bozzys.ui.theme.Text
import com.iscs.bozzys.utils.DateUtil.getShowDateOrTime
import com.iscs.bozzys.utils.getRoleName

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeCompose(pv: PaddingValues, zIndex: Float, vm: VMHome) {
    val state by vm.state.collectAsState()
    Column(
        modifier = Modifier
            .fillMaxSize()
            .zIndex(zIndex)
            .background(MaterialTheme.colorScheme.background)
            .pointerInput(Unit) {},
    ) {
        // 顶部工具栏
        TopToolBar(pv, vm)
        PullToRefreshBox(state.isHomeTabRefresh, onRefresh = {
            vm.onRefreshHomeTab()
        }) {
            Column(Modifier.fillMaxSize()) {
                Box {
                    TaskList(pv, vm)
                    TODO(vm)
                }
            }
        }
    }
}

/**
 * 顶部工具栏
 */
@Composable
private fun TopToolBar(pv: PaddingValues, vm: VMHome) {
    val ctx = LocalContext.current
    val state by vm.state.collectAsState()
    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(start = 16.dp, end = 10.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .clip(RoundedCornerShape(50)),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    painter = painterResource(R.drawable.user),
                    modifier = Modifier
                        .fillMaxSize()
                        .background(Color(0xFFFFD700))
                        .padding(10.dp),
                    contentDescription = null,
                    tint = Color.White
                )
                AsyncImage(
                    model = state.user.avatar,
                    contentDescription = null,
                    modifier = Modifier.fillMaxSize(),
                    contentScale = ContentScale.Crop
                )
            }
            Column(Modifier.padding(horizontal = 10.dp)) {
                Text(
                    state.user.nickname,
                    fontSize = 16.sp,
                    lineHeight = 16.sp,
                    fontWeight = FontWeight.Medium,
                    color = Color.White
                )
                Text(
                    state.roles.getRoleName(),
                    fontSize = 12.sp,
                    lineHeight = 12.sp,
                    color = Color.White.copy(alpha = 0.8f)
                )
            }
            Spacer(Modifier.weight(1f))
            Box(modifier = Modifier.fillMaxHeight(), contentAlignment = Alignment.Center) {
                Icon(
                    painter = painterResource(R.drawable.bell),
                    contentDescription = null,
                    modifier = Modifier
                        .size(36.dp)
                        .clip(RoundedCornerShape(6.dp))
                        .clickable(onClick = { ctx.openPageMessage() })
                        .padding(6.dp),
                    tint = Color.White
                )
                if (state.msgCount > 0) Text(
                    if (state.msgCount > 99) "99+" else "${state.msgCount}",
                    color = Color.White,
                    modifier = Modifier
                        .offset(x = 12.dp, y = 15.dp)
                        .defaultMinSize(14.dp, 14.dp)
                        .clip(RoundedCornerShape(14.dp))
                        .background(Color.Red)
                        .align(Alignment.TopCenter)
                        .padding(top = 1.dp)
                        .padding(horizontal = 2.dp),
                    textAlign = TextAlign.Center,
                    fontSize = 10.sp,
                    lineHeight = 10.sp
                )
            }
            // 待归还设备入口
            Box(modifier = Modifier.fillMaxHeight(), contentAlignment = Alignment.Center) {
                Icon(
                    painter = painterResource(R.drawable.return_device),
                    contentDescription = null,
                    modifier = Modifier
                        .padding(start = 8.dp)
                        .size(36.dp)
                        .clip(RoundedCornerShape(6.dp))
                        .clickable(onClick = { ctx.openPageReturnDevice() })
                        .padding(7.dp),
                    tint = Color.White
                )
                if (false) Text(
                    "1",
                    color = Color.White,
                    modifier = Modifier
                        .offset(x = 12.dp, y = 15.dp)
                        .defaultMinSize(14.dp, 14.dp)
                        .clip(RoundedCornerShape(14.dp))
                        .background(Color.Red)
                        .align(Alignment.TopCenter)
                        .padding(top = 1.dp)
                        .padding(horizontal = 2.dp),
                    textAlign = TextAlign.Center,
                    fontSize = 10.sp,
                    lineHeight = 10.sp
                )
            }
        }
    }
}

/**
 * 待办任务
 */
@Composable
private fun TODO(vmHome: VMHome) {
    val state by vmHome.state.collectAsState()
    Column(
        Modifier
            .fillMaxWidth()
            .background(MaterialTheme.colorScheme.background)
            .padding(top = 3.dp)
    ) {
        Text(
            "今天有${state.todoCountRunning}个待办任务", Modifier
                .fillMaxWidth()
                .height(51.dp)
                .background(Color(0xFFE6F7FF)),
            fontSize = 14.sp,
            lineHeight = 51.sp,
            color = Text,
            textAlign = TextAlign.Center
        )
        Row(Modifier.padding(vertical = 15.dp)) {
            Spacer(Modifier.width(10.dp))
            Column(
                Modifier
                    .weight(1f)
                    .height(80.dp)
                    .clip(RoundedCornerShape(12.dp))
                    .background(MaterialTheme.colorScheme.primary.copy(alpha = 0.1f))
                    .clickable {
                        vmHome.onTaskProgressClick()
                    },
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Text(
                    "${state.todoCountRunning}",
                    fontSize = 24.sp,
                    lineHeight = 24.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFFFFA500)
                )
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        painterResource(R.drawable.job_ing),
                        contentDescription = null,
                        modifier = Modifier
                            .padding(end = 5.dp)
                            .size(16.dp),
                        tint = Text
                    )
                    Text(
                        "进行中",
                        fontSize = 14.sp,
                        color = Text,
                        fontWeight = FontWeight.Bold,
                    )
                }

            }
            Spacer(Modifier.width(10.dp))
            Column(
                Modifier
                    .weight(1f)
                    .height(80.dp)
                    .clip(RoundedCornerShape(12.dp))
                    .background(MaterialTheme.colorScheme.primary.copy(alpha = 0.1f))
                    .clickable {
                        vmHome.onTaskFinishClick()
                    },
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Text(
                    "${state.todoCountFinish}",
                    fontSize = 24.sp,
                    lineHeight = 24.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF32CD32)
                )
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        painterResource(R.drawable.job_finish),
                        contentDescription = null,
                        modifier = Modifier
                            .padding(end = 5.dp)
                            .size(16.dp),
                        tint = Text
                    )
                    Text(
                        "本月完成",
                        fontSize = 14.sp,
                        color = Text,
                        fontWeight = FontWeight.Bold,
                    )
                }

            }
            Spacer(Modifier.width(10.dp))
        }
    }
}

/**
 * 待办列表
 */
@Composable
private fun TaskList(pv: PaddingValues, vm: VMHome) {
    val ctx = LocalContext.current
    val state by vm.state.collectAsState()
    Column(
        Modifier
            .padding(bottom = pv.calculateBottomPadding())
            .fillMaxSize()
            .verticalScroll(state = rememberScrollState())
            .padding(top = 164.dp)
    ) {
        Row(
            Modifier
                .padding(horizontal = 16.dp)
                .fillMaxWidth()
                .height(36.dp)
                .clickable(
                    indication = null,
                    interactionSource = remember { MutableInteractionSource() },
                    onClick = {
                        vm.onTaskProgressClick()
                    }),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text("当前任务", fontSize = 14.sp, fontWeight = FontWeight.Medium, color = Text)
            Spacer(Modifier.weight(1f))
            Text("查看全部", fontSize = 14.sp, color = Color(0xFF1E90FF))
        }
        if (state.homeTasks.isEmpty()) CardBox(
            modifier = Modifier
                .padding(horizontal = 16.dp, vertical = 5.dp)
                .fillMaxWidth()
                .height(102.dp),
            shadowBlur = 6.dp
        ) {
            Column(
                Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Text("您当前暂无任务", fontSize = 14.sp, color = Text)
            }
        }
        Column(Modifier.fillMaxWidth()) {
            state.homeTasks.forEachIndexed { idx, task ->
                key(task.workId) {
                    TaskListItem(task)
                }
            }
        }
        Row(
            Modifier
                .padding(horizontal = 16.dp)
                .fillMaxWidth()
                .height(36.dp)
                .clickable(
                    indication = null,
                    interactionSource = remember { MutableInteractionSource() },
                    onClick = {
                        ctx.openPageMessage()
                    }),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Text("最新消息", fontSize = 14.sp, fontWeight = FontWeight.Medium, color = Text)
            Spacer(Modifier.weight(1f))
            Text("全部消息", fontSize = 14.sp, color = Color(0xFF1E90FF))
        }
        if (state.messageList.isEmpty()) CardBox(
            modifier = Modifier
                .padding(horizontal = 16.dp, vertical = 5.dp)
                .fillMaxWidth()
                .height(102.dp),
            shadowBlur = 6.dp
        ) {
            Column(
                Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Text("您当前暂无新消息", fontSize = 14.sp, color = Text)
            }
        }
        Column(
            Modifier
                .padding(horizontal = 16.dp)
                .fillMaxWidth()
        ) {
            state.messageList.forEach { msg -> key(msg.id) { MessageListItem(msg, vm) } }
        }
    }
}

@Composable
fun MessageListItem(msg: Message, vm: VMHome) {
    CardBox(modifier = Modifier.padding(vertical = 8.dp)) {
        Row(
            Modifier
                .fillMaxWidth()
                .height(122.dp)
                .clickable(onClick = { vm.onMessage(msg) })
                .padding(16.dp)
        ) {
            Column(
                Modifier
                    .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("作业管理", fontSize = 12.sp, color = Color(0xFF999999))
                    Spacer(Modifier.weight(1f))
                    Text(
                        msg.createTime.getShowDateOrTime(),
                        fontSize = 12.sp,
                        color = Text.copy(alpha = 0.6f)
                    )
                }
            }
//            Spacer(
//                Modifier
//                    .size(8.dp)
//                    .clip(RoundedCornerShape(50))
//                    .background(if (msg.readStatus) Color.Transparent else Color(0xFFFF4500))
//                    .align(Alignment.CenterVertically)
//            )
        }
    }
}