package com.example.ops_android.ui.order

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
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.compose.viewModel
import com.example.ops_android.ui.LocalAppContainer
import kotlinx.coroutines.launch

val STATUS_FLOW = listOf("pending", "ordered", "arrived", "received")
val STATUS_FLOW_LABELS = mapOf(
    "pending" to "待处理",
    "ordered" to "已订购",
    "arrived" to "已到货",
    "received" to "已收货",
    "lost" to "丢失",
    "returned" to "退货"
)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun OrderDetailScreen(
    orderId: Int,
    onBack: () -> Unit
) {
    val repository = LocalAppContainer.current.orderRepository
    val viewModel: OrderDetailViewModel = viewModel(
        key = "order_$orderId",
        factory = OrderDetailViewModel.Factory(repository, orderId)
    )
    val uiState by viewModel.uiState.collectAsState()

    val order = uiState.order

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("订单详情") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, null, tint = Color.White)
                    }
                },
                actions = {
                    val scope = rememberCoroutineScope()
                    order?.let { o ->
                        val printerManager = LocalAppContainer.current.printerManager
                        if (printerManager != null) {
                            val sm = LocalAppContainer.current.sessionManager
                            IconButton(onClick = {
                                scope.launch {
                                    com.example.ops_android.printer.PrintHelper.printOrderLabel(printerManager, o, sm.cachedBlackMarkEnabled, sm.cachedUnwindMm)
                                }
                            }) {
                                Icon(Icons.Default.Print, "打印", tint = Color.White)
                            }
                        }
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color(0xFF667EEA),
                    titleContentColor = Color.White
                )
            )
        }
    ) { padding ->
        if (uiState.isLoading) {
            Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) {
                CircularProgressIndicator()
            }
            return@Scaffold
        }

        if (order == null) {
            Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) {
                Text(uiState.errorMessage ?: "加载失败")
            }
            return@Scaffold
        }

        LazyColumn(
            modifier = Modifier.fillMaxSize().padding(padding).padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            item {
                Text("基本信息", fontWeight = FontWeight.Bold, fontSize = 18.sp)
                Card(modifier = Modifier.fillMaxWidth()) {
                    Column(Modifier.padding(16.dp)) {
                        DetailRow("标题", order.title ?: "-")
                        DetailRow("状态", STATUS_FLOW_LABELS[order.status] ?: order.status ?: "-")
                        DetailRow("备注", order.remark ?: "-")
                        DetailRow("链接", order.link ?: "-")
                        DetailRow("创建时间", order.created_at ?: "-")
                    }
                }
            }

            order.style_tags?.let { tags ->
                if (tags.isNotEmpty()) {
                    item {
                        Text("款式标签", fontWeight = FontWeight.Bold, fontSize = 16.sp)
                        Card(modifier = Modifier.fillMaxWidth()) {
                            Column(Modifier.padding(16.dp)) {
                                tags.forEach { Text("- $it", fontSize = 14.sp) }
                            }
                        }
                    }
                }
            }

            order.costs?.let { costs ->
                if (costs.isNotEmpty()) {
                    item {
                        Text("费用明细", fontWeight = FontWeight.Bold, fontSize = 16.sp)
                        Card(modifier = Modifier.fillMaxWidth()) {
                            Column(Modifier.padding(16.dp)) {
                                costs.forEach { cost ->
                                    Row(
                                        Modifier.fillMaxWidth().padding(vertical = 4.dp),
                                        horizontalArrangement = Arrangement.SpaceBetween
                                    ) {
                                        Text("${cost.amount} ${cost.currency}")
                                        Text(cost.remark ?: "", color = Color.Gray)
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Status timeline
            order.status_logs?.let { logs ->
                if (logs.isNotEmpty()) {
                    item {
                        Text("状态时间线", fontWeight = FontWeight.Bold, fontSize = 16.sp)
                    }
                    items(logs) { log ->
                        TimelineItem(log)
                    }
                }
            }

            // Status change buttons
            item {
                Spacer(Modifier.height(8.dp))
                Text("状态变更", fontWeight = FontWeight.Bold, fontSize = 16.sp)
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    STATUS_FLOW.forEach { status ->
                        if (status != order.status) {
                            FilterChip(
                                selected = false,
                                onClick = { viewModel.showStatusDialog(status) },
                                label = { Text(STATUS_FLOW_LABELS[status] ?: status, fontSize = 12.sp) }
                            )
                        }
                    }
                    FilterChip(
                        selected = false,
                        onClick = { viewModel.showStatusDialog("lost") },
                        label = { Text("丢失", fontSize = 12.sp, color = Color(0xFFF44336)) }
                    )
                    FilterChip(
                        selected = false,
                        onClick = { viewModel.showStatusDialog("returned") },
                        label = { Text("退货", fontSize = 12.sp, color = Color(0xFF9C27B0)) }
                    )
                }
            }
        }
    }

    // Status change dialog
    if (uiState.showStatusDialog) {
        val statusLabel = STATUS_FLOW_LABELS[uiState.selectedStatus] ?: uiState.selectedStatus
        AlertDialog(
            onDismissRequest = { viewModel.dismissStatusDialog() },
            title = { Text("变更状态为「$statusLabel」") },
            text = {
                Column {
                    Text("请输入备注（可选）：")
                    Spacer(Modifier.height(8.dp))
                    OutlinedTextField(
                        value = uiState.statusComment,
                        onValueChange = viewModel::onStatusCommentChange,
                        modifier = Modifier.fillMaxWidth(),
                        minLines = 2,
                        placeholder = { Text("备注信息") }
                    )
                }
            },
            confirmButton = {
                Button(
                    onClick = { viewModel.submitStatusChange() },
                    enabled = !uiState.isSubmitting
                ) { Text("确认") }
            },
            dismissButton = {
                TextButton(onClick = { viewModel.dismissStatusDialog() }) { 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)
    }
}

@Composable
private fun TimelineItem(log: com.example.ops_android.data.model.StatusLog) {
    Card(modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(8.dp)) {
        Column(Modifier.padding(12.dp)) {
            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                Text(
                    STATUS_FLOW_LABELS[log.status] ?: log.status ?: "",
                    fontWeight = FontWeight.Medium,
                    color = Color(0xFF667EEA)
                )
                Text(log.created_at ?: "", fontSize = 12.sp, color = Color.Gray)
            }
            log.comment?.let {
                if (it.isNotBlank()) {
                    Spacer(Modifier.height(4.dp))
                    Text(it, fontSize = 14.sp)
                }
            }
        }
    }
}
