package com.example.ops_android.ui.workorder

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Print
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.ops_android.data.model.Commit
import com.example.ops_android.data.model.WorkOrder
import com.example.ops_android.data.repository.WorkOrderRepository
import com.example.ops_android.ui.LocalAppContainer
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class WorkOrderDetailUiState(
    val workOrder: WorkOrder? = null, val isLoading: Boolean = false, val errorMessage: String? = null,
    val showCommitDialog: Boolean = false, val commitStatus: String = "", val commitComment: String = "", val isSubmitting: Boolean = false
)

class WorkOrderDetailViewModel(repo: WorkOrderRepository, private val id: Int) : ViewModel() {
    private val _s = MutableStateFlow(WorkOrderDetailUiState()); val s: StateFlow<WorkOrderDetailUiState> = _s.asStateFlow()
    private val repository = repo

    init { load() }
    fun load() { viewModelScope.launch { _s.value = _s.value.copy(isLoading = true); repository.get(id).fold(onSuccess = { _s.value = _s.value.copy(workOrder = it, isLoading = false) }, onFailure = { _s.value = _s.value.copy(isLoading = false, errorMessage = it.message) }) } }
    fun showCommitDialog(status: String) { _s.value = _s.value.copy(showCommitDialog = true, commitStatus = status, commitComment = "") }
    fun dismissCommitDialog() { _s.value = _s.value.copy(showCommitDialog = false) }
    fun onCommentChange(v: String) { _s.value = _s.value.copy(commitComment = v) }
    fun submitCommit() { viewModelScope.launch {
        val st = _s.value; _s.value = st.copy(isSubmitting = true)
        repository.commit(id, st.commitStatus.ifBlank { null }, st.commitComment.ifBlank { null }, null)
            .fold(onSuccess = { _s.value = _s.value.copy(showCommitDialog = false, isSubmitting = false); load() }, onFailure = { _s.value = _s.value.copy(isSubmitting = false, errorMessage = it.message) })
    } }

    class Factory(private val repo: WorkOrderRepository, private val id: Int) : ViewModelProvider.Factory {
        @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(c: Class<T>): T = WorkOrderDetailViewModel(repo, id) as T
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WorkOrderDetailScreen(id: Int, onBack: () -> Unit) {
    val vm: WorkOrderDetailViewModel = viewModel(key = "wo_$id", factory = WorkOrderDetailViewModel.Factory(LocalAppContainer.current.workOrderRepository, id))
    val s by vm.s.collectAsState(); val wo = s.workOrder
    val sl = mapOf("pending" to "待处理", "checked" to "已检查", "parts_ordered" to "待配件", "repaired" to "已修复", "returned" to "已返还", "unrepairable" to "不可修")

    Scaffold(topBar = {
        TopAppBar(title = { Text("工单详情") },
            navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, null, tint = Color.White) } },
            actions = {
                val scope = rememberCoroutineScope()
                wo?.let { wo_ ->
                    val printerManager = com.example.ops_android.ui.LocalAppContainer.current.printerManager
                    if (printerManager != null) {
                        val sm = com.example.ops_android.ui.LocalAppContainer.current.sessionManager
                        IconButton(onClick = {
                            scope.launch { com.example.ops_android.printer.PrintHelper.printWorkOrderLabel(printerManager, wo_, labelWidthMm = sm.cachedLabelWidthMm, labelHeightMm = sm.cachedLabelHeightMm, blackMarkEnabled = sm.cachedBlackMarkEnabled, unwindMm = sm.cachedUnwindMm, printRetractMm = sm.cachedPrintRetractMm) }
                        }) { Icon(Icons.Default.Print, "打印", tint = Color.White) }
                    }
                }
            },
            colors = TopAppBarDefaults.topAppBarColors(containerColor = Color(0xFF667EEA), titleContentColor = Color.White))
    }) { padding ->
        if (s.isLoading) { Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) { CircularProgressIndicator() }; return@Scaffold }
        if (wo == null) { Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) { Text(s.errorMessage ?: "加载失败") }; return@Scaffold }

        LazyColumn(Modifier.fillMaxSize().padding(padding).padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
            item { Text("基本信息", fontWeight = FontWeight.Bold, fontSize = 18.sp); Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { DetailRow("标题", wo.title ?: "-"); DetailRow("状态", sl[wo.status] ?: wo.status ?: "-"); DetailRow("描述", wo.description ?: "-"); DetailRow("创建时间", wo.created_at ?: "-") } } }

            wo.commits?.let { commits ->
                if (commits.isNotEmpty()) {
                    item { Text("提交记录", fontWeight = FontWeight.Bold, fontSize = 16.sp) }
                    items(commits) { c: Commit ->
                        Card(Modifier.fillMaxWidth()) {
                            Column(Modifier.padding(12.dp)) {
                                Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text(sl[c.status] ?: c.status ?: "", fontWeight = FontWeight.Medium, color = Color(0xFF667EEA)); Text(c.created_at ?: "", fontSize = 12.sp, color = Color.Gray) }
                                c.comment?.takeIf { it.isNotBlank() }?.let { Spacer(Modifier.height(4.dp)); Text(it, fontSize = 14.sp) }
                            }
                        }
                    }
                }
            }

            item { Spacer(Modifier.height(8.dp)); Text("流转状态", fontWeight = FontWeight.Bold, fontSize = 16.sp)
                Row(Modifier.fillMaxWidth().wrapContentHeight(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                    listOf("checked", "parts_ordered", "repaired", "returned", "unrepairable").forEach { st ->
                        if (st != wo.status) FilterChip(selected = false, onClick = { vm.showCommitDialog(st) }, label = { Text(sl[st] ?: st, fontSize = 12.sp) })
                    }
                }
            }
        }
    }

    if (s.showCommitDialog) AlertDialog(onDismissRequest = { vm.dismissCommitDialog() }, title = { Text("流转为「${sl[s.commitStatus] ?: s.commitStatus}」") }, text = { Column { Text("备注（可选）："); Spacer(Modifier.height(8.dp)); OutlinedTextField(value = s.commitComment, onValueChange = vm::onCommentChange, Modifier.fillMaxWidth(), minLines = 2, placeholder = { Text("备注") }) } }, confirmButton = { Button(onClick = { vm.submitCommit() }, enabled = !s.isSubmitting) { Text("确认") } }, dismissButton = { TextButton(onClick = { vm.dismissCommitDialog() }) { Text("取消") } })
}

@Composable
private fun DetailRow(label: String, value: String) {
    Row(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { Text(label, color = Color.Gray, modifier = Modifier.width(80.dp)); Text(value) }
}
