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

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.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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
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.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalTextStyle
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.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
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.graphics.SolidColor
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
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.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import com.iscs.bozzys.R
import com.iscs.bozzys.ui.common.Empty
import com.iscs.bozzys.ui.pages.compose.JobListItem
import com.iscs.bozzys.ui.pages.create.job.openPageCreateJob
import com.iscs.bozzys.ui.pages.vm.StatePage
import com.iscs.bozzys.ui.pages.vm.VMHome
import com.iscs.bozzys.ui.theme.Main
import com.iscs.bozzys.ui.theme.Text
import com.iscs.bozzys.utils.isAdmin

@Composable
fun JobsCompose(pv: PaddingValues, zIndex: Float, vm: VMHome) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .zIndex(zIndex)
            .background(MaterialTheme.colorScheme.background)
            .pointerInput(Unit) {},
    ) {
        // 顶部工具栏
        Column(
            modifier = Modifier
                .padding(bottom = pv.calculateBottomPadding())
                .fillMaxSize()
        ) {
            TopToolBar(pv, vm)
            FilterBar(vm)
            TaskList(vm)
        }
    }
}

/**
 * 顶部工具栏
 */
@Composable
private fun TopToolBar(pv: PaddingValues, vm: VMHome) {
    val state by vm.state.collectAsState()
    val ctx = LocalContext.current
    val keyboard = LocalSoftwareKeyboardController.current
    var keywords by remember { mutableStateOf("") }
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(
                brush = Brush.horizontalGradient(
                    listOf(
                        Color(0xFFFF8C00),
                        Color(0xFFFFA500)
                    )
                )
            )
            .padding(top = pv.calculateTopPadding() + 8.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(start = 16.dp, end = 10.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text("我的作业", fontSize = 18.sp, color = Color.White, fontWeight = FontWeight.Medium)
            Spacer(Modifier.weight(1f))
            if (state.roles.isAdmin()) {
                Icon(
                    painter = painterResource(R.drawable.add),
                    contentDescription = null,
                    modifier = Modifier
                        .size(36.dp)
                        .clip(RoundedCornerShape(6.dp))
                        .clickable(onClick = {
                            // 前期SOP没有做流程选择，这里先直接跳转到创建页面
                            // ctx.openPageSelectJobType()
                            ctx.openPageCreateJob(0)
                            // 测试流程模板编辑数据
                            // ctx.openPageEditStep(69)
                            // 测试发布作业
                            // ctx.openPagePushJob(71)
                        })
                        .padding(5.dp),
                    tint = Color.White
                )
            } else {
                Spacer(modifier = Modifier.size(36.dp))
            }

        }
        Row(
            Modifier
                .background(
                    brush = Brush.horizontalGradient(
                        listOf(
                            Color(0xFFFF8C00),
                            Color(0xFFFFA500)
                        )
                    )
                )
                .padding(horizontal = 16.dp, vertical = 8.dp)
        ) {
            BasicTextField(
                keywords,
                onValueChange = { keywords = it },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(40.dp)
                    .clip(RoundedCornerShape(50))
                    .background(
                        brush = Brush.horizontalGradient(
                            listOf(
                                Color(0xFFFFA126),
                                Color(0xFFFFB126)
                            )
                        )
                    )
                    .padding(horizontal = 16.dp),
                singleLine = true,
                textStyle = LocalTextStyle.current.copy(
                    fontSize = 16.sp,
                    lineHeight = 18.sp,
                    color = Color.White
                ),
                decorationBox = { innerTextField ->
                    Box(contentAlignment = Alignment.CenterStart) {
                        innerTextField()
                        if (keywords.isEmpty()) {
                            val text = "搜索作业名称或作业编号..."
                            Text(
                                text,
                                color = Color.White.copy(alpha = 0.8f),
                                fontSize = 16.sp,
                                lineHeight = 18.sp
                            )
                        }
                    }
                },
                cursorBrush = SolidColor(Color.White),
                keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
                keyboardActions = KeyboardActions(onSearch = {
                    keyboard?.hide()
                    vm.getJobList(
                        StatePage(
                            page = 1,
                            type = "",
                            keywords = keywords,
                            isRefresh = true
                        )
                    )
                })
            )
        }
    }
}

/**
 * 过滤条
 */
@Composable
private fun FilterBar(vm: VMHome) {
    val keyboard = LocalSoftwareKeyboardController.current
    val state by vm.state.collectAsState()
    Row(
        modifier = Modifier
            .padding(vertical = 5.dp)
            .fillMaxWidth()
            .padding(horizontal = 16.dp)
            .padding(top = 6.dp)
    ) {
        Text(
            "进行中",
            fontSize = 14.sp,
            color = if (state.jobPage.type == "running") Color.White else Color(0xFF666666),
            modifier = Modifier
                .padding(end = 10.dp)
                .clip(RoundedCornerShape(50))
                .background(color = if (state.jobPage.type == "running") Main else Color(0xFFF0F0F0))
                .clickable(onClick = {
                    keyboard?.hide()
                    vm.getJobList(
                        state.jobPage.copy(
                            page = 1,
                            type = "running",
                            keywords = "",
                            noMore = false,
                            isRefresh = true
                        )
                    )
                })
                .padding(horizontal = 12.dp, vertical = 5.dp),
        )
        Text(
            "待发布",
            fontSize = 14.sp,
            color = if (state.jobPage.type == "unreleased") Color.White else Color(0xFF666666),
            modifier = Modifier
                .padding(end = 10.dp)
                .clip(RoundedCornerShape(50))
                .background(
                    color = if (state.jobPage.type == "unreleased") Main else Color(
                        0xFFF0F0F0
                    )
                )
                .clickable(onClick = {
                    keyboard?.hide()
                    vm.getJobList(
                        state.jobPage.copy(
                            page = 1,
                            type = "unreleased",
                            keywords = "",
                            noMore = false,
                            isRefresh = true
                        )
                    )
                })
                .padding(horizontal = 12.dp, vertical = 5.dp),
        )
        Text(
            "已完成",
            fontSize = 14.sp,
            color = if (state.jobPage.type == "completed") Color.White else Color(0xFF666666),
            modifier = Modifier
                .padding(end = 10.dp)
                .clip(RoundedCornerShape(50))
                .background(
                    color = if (state.jobPage.type == "completed") Main else Color(
                        0xFFF0F0F0
                    )
                )
                .clickable(onClick = {
                    keyboard?.hide()
                    vm.getJobList(
                        state.jobPage.copy(
                            page = 1,
                            type = "completed",
                            keywords = "",
                            noMore = false,
                            isRefresh = true
                        )
                    )
                })
                .padding(horizontal = 12.dp, vertical = 5.dp),
        )
        Text(
            "全部",
            fontSize = 14.sp,
            color = if (state.jobPage.type == "") Color.White else Color(0xFF666666),
            modifier = Modifier
                .padding(end = 10.dp)
                .clip(RoundedCornerShape(50))
                .background(color = if (state.jobPage.type == "") Main else Color(0xFFF0F0F0))
                .clickable(onClick = {
                    keyboard?.hide()
                    vm.getJobList(
                        state.jobPage.copy(
                            page = 1,
                            type = "",
                            keywords = "",
                            noMore = false,
                            isRefresh = true
                        )
                    )
                })
                .padding(horizontal = 12.dp, vertical = 5.dp),
        )
    }
}

/**
 * 任务列表数据
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun TaskList(vm: VMHome) {
    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.jobList.isNotEmpty() && !state.jobPage.noMore) {
            vm.getJobList(state.jobPage.copy(page = state.jobPage.page + 1, isRefresh = false))
        }
    }
    Box {
        PullToRefreshBox(state.jobPage.isRefresh, onRefresh = {
            vm.getJobList(state.jobPage.copy(page = 1, noMore = false, isRefresh = true))
        }, modifier = Modifier.fillMaxSize()) {
            Box(
                modifier = Modifier
                    .padding(top = 5.dp)
                    .fillMaxSize()
            ) {
                LazyColumn(
                    state = listState,
                    modifier = Modifier
                        .fillMaxSize()
                ) {
                    items(state.jobList) { item ->
                        JobListItem(item)
                    }
                    // 数据不为空才会显示加载中
                    if (state.jobList.isNotEmpty()) item {
                        Text(
                            if (state.jobPage.noMore) "没有更多数据" else "加载更多数据中...",
                            fontSize = 12.sp,
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 10.dp),
                            textAlign = TextAlign.Center,
                            color = Text.copy(alpha = 0.6f)
                        )
                    }
                }
                // 悬浮在列表的顶部
//                Box(Modifier.background(Color.White)) {
//                    DateTitle("${list[topIdx]}")
//                }
                if (state.jobList.isEmpty()) Empty(tips = "暂无数据")

            }
        }
    }
}

/**
 * 消息标题
 */
@Composable
private fun DateTitle(title: String) {
    Text(
        title,
        fontSize = 16.sp,
        lineHeight = 22.sp,
        fontWeight = FontWeight.Medium,
        color = Text,
        modifier = Modifier
            .padding(bottom = 10.dp)
            .fillMaxWidth()
            .height(22.dp),
    )
}