package com.example.ops_android.ui.order

import androidx.compose.foundation.clickable
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.filled.Add
import androidx.compose.material3.*
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
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.data.model.PurchaseOrder
import com.example.ops_android.ui.LocalAppContainer

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun OrderListScreen(
    onOrderClick: (Int) -> Unit,
    onAddClick: () -> Unit,
    viewModel: OrderListViewModel = viewModel(factory = OrderListViewModel.Factory(LocalAppContainer.current.orderRepository))
) {
    val uiState by viewModel.uiState.collectAsState()

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("采购订单") },
                actions = {
                    IconButton(onClick = onAddClick) {
                        Icon(Icons.Default.Add, "新建", tint = Color.White)
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color(0xFF667EEA),
                    titleContentColor = Color.White
                )
            )
        },
        floatingActionButton = {
            FloatingActionButton(
                onClick = onAddClick,
                containerColor = Color(0xFF667EEA)
            ) {
                Icon(Icons.Default.Add, "新建", tint = Color.White)
            }
        }
    ) { padding ->
        Column(modifier = Modifier.padding(padding)) {
            // Status filter tabs
            PrimaryScrollableTabRow(
                selectedTabIndex = ORDER_STATUSES.indexOfFirst { it.first == uiState.selectedStatus }.coerceAtLeast(0),
                modifier = Modifier.fillMaxWidth(),
                edgePadding = 8.dp
            ) {
                ORDER_STATUSES.forEachIndexed { index, (status, label) ->
                    Tab(
                        selected = uiState.selectedStatus == status,
                        onClick = { viewModel.selectStatus(status) },
                        text = {
                            Text(
                                label,
                                fontSize = 13.sp,
                                fontWeight = if (uiState.selectedStatus == status) FontWeight.Bold else FontWeight.Normal
                            )
                        }
                    )
                }
            }

            when {
                uiState.isLoading -> {
                    Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                        CircularProgressIndicator()
                    }
                }
                uiState.errorMessage != null -> {
                    Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                        Column(horizontalAlignment = Alignment.CenterHorizontally) {
                            Text(uiState.errorMessage!!, color = Color.Red)
                            Spacer(Modifier.height(8.dp))
                            Button(onClick = { viewModel.refresh() }) { Text("重试") }
                        }
                    }
                }
                else -> {
                    PullToRefreshBox(
                        isRefreshing = uiState.isRefreshing,
                        onRefresh = { viewModel.refresh() },
                        modifier = Modifier.fillMaxSize()
                    ) {
                        LazyColumn(
                            modifier = Modifier.fillMaxSize(),
                            contentPadding = PaddingValues(8.dp),
                            verticalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            items(uiState.orders, key = { it.id }) { order ->
                                OrderListItem(
                                    order = order,
                                    onClick = { onOrderClick(order.id) }
                                )
                            }

                            if (uiState.isLoadingMore) {
                                item {
                                    Box(Modifier.fillMaxWidth().padding(16.dp), contentAlignment = Alignment.Center) {
                                        CircularProgressIndicator(modifier = Modifier.size(24.dp))
                                    }
                                }
                            }

                            // infinite scroll trigger
                            item {
                                LaunchedEffect(Unit) { viewModel.loadMore() }
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun OrderListItem(order: PurchaseOrder, onClick: () -> Unit) {
    val statusColors = mapOf(
        "pending" to Color(0xFFFF9800),
        "ordered" to Color(0xFF2196F3),
        "arrived" to Color(0xFF03A9F4),
        "received" to Color(0xFF4CAF50),
        "lost" to Color(0xFFF44336),
        "returned" to Color(0xFF9C27B0)
    )
    val statusLabels = mapOf(
        "pending" to "待处理",
        "ordered" to "已订购",
        "arrived" to "已到货",
        "received" to "已收货",
        "lost" to "丢失",
        "returned" to "退货"
    )

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onClick() }
    ) {
        Row(
            modifier = Modifier.padding(12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(modifier = Modifier.weight(1f)) {
                Text(order.title ?: "无标题", fontWeight = FontWeight.Medium, fontSize = 15.sp)
                Spacer(Modifier.height(4.dp))
                Text(order.created_at ?: "", fontSize = 12.sp, color = Color.Gray)
            }
            Spacer(Modifier.width(8.dp))
            Surface(
                shape = MaterialTheme.shapes.small,
                color = statusColors[order.status]?.copy(alpha = 0.15f) ?: Color.Gray.copy(alpha = 0.15f)
            ) {
                Text(
                    statusLabels[order.status] ?: order.status ?: "",
                    modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
                    fontSize = 12.sp,
                    color = statusColors[order.status] ?: Color.Gray
                )
            }
        }
    }
}
