package com.example.ops_android.ui.warehouse

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.material.icons.filled.ChevronRight
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.Inventory
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.Container
import com.example.ops_android.data.model.Item
import com.example.ops_android.ui.LocalAppContainer

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WarehouseScreen(
    onItemClick: (Int) -> Unit,
    onAddItemClick: (Int) -> Unit = {},
    viewModel: WarehouseViewModel = viewModel(factory = WarehouseViewModel.Factory(LocalAppContainer.current.warehouseRepository))
) {
    val s by viewModel.s.collectAsState()
    var showFabMenu by remember { mutableStateOf(false) }
    var showAddContainer by remember { mutableStateOf(false) }
    var newContainerName by remember { mutableStateOf("") }

    Scaffold(
        topBar = { TopAppBar(title = { Text("仓库") }, colors = TopAppBarDefaults.topAppBarColors(containerColor = Color(0xFF667EEA), titleContentColor = Color.White)) },
        floatingActionButton = { FloatingActionButton(onClick = { showFabMenu = true }, containerColor = Color(0xFF667EEA)) { Icon(Icons.Default.Add, "新建", tint = Color.White) } }
    ) { padding ->
        Column(Modifier.padding(padding)) {
            // Breadcrumb
            PrimaryScrollableTabRow(selectedTabIndex = s.breadcrumb.size - 1) {
                s.breadcrumb.forEachIndexed { idx, (id, name) ->
                    Tab(selected = idx == s.breadcrumb.size - 1, onClick = { viewModel.navigateToBreadcrumb(idx) }, text = { Text(name, fontSize = 12.sp) })
                }
            }

            // Tabs: All / Items Only
            Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                FilterChip(selected = !s.showItemsOnly, onClick = { viewModel.toggleItemsOnly() }, label = { Text("全部") })
                FilterChip(selected = s.showItemsOnly, onClick = { viewModel.toggleItemsOnly() }, label = { Text("仅物品") })
            }

            // Error
            s.errorMessage?.let { error ->
                Card(
                    Modifier.fillMaxWidth().padding(horizontal = 16.dp),
                    colors = CardDefaults.cardColors(containerColor = Color(0xFFFFEBEE))
                ) {
                    Text(error, modifier = Modifier.padding(12.dp), color = Color(0xFFC62828), fontSize = 13.sp)
                }
            }

            if (s.isLoading && s.containers.isEmpty()) Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
            else PullToRefreshBox(
                isRefreshing = s.isRefreshing,
                onRefresh = { viewModel.refresh() },
                modifier = Modifier.fillMaxSize()
            ) {
                LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
                    if (!s.showItemsOnly) {
                        items(s.containers) { container ->
                            ContainerItem(container) { viewModel.navigateTo(container.id, container.name ?: "未命名") }
                        }
                    }
                    items(s.items) { item ->
                        ItemRow(item) { onItemClick(item.id) }
                    }
                }
            }
        }
    }

    // FAB menu dialog
    if (showFabMenu) {
        AlertDialog(
            onDismissRequest = { showFabMenu = false },
            title = { Text("新建") },
            text = {
                Column {
                    TextButton(onClick = {
                        showFabMenu = false
                        newContainerName = ""
                        showAddContainer = true
                    }, modifier = Modifier.fillMaxWidth()) {
                        Icon(Icons.Default.Folder, null, Modifier.size(24.dp))
                        Spacer(Modifier.width(12.dp))
                        Text("新建容器", modifier = Modifier.weight(1f))
                    }
                    TextButton(onClick = {
                        showFabMenu = false
                        onAddItemClick(s.breadcrumb.last().first)
                    }, modifier = Modifier.fillMaxWidth()) {
                        Icon(Icons.Default.Inventory, null, Modifier.size(24.dp))
                        Spacer(Modifier.width(12.dp))
                        Text("新建物品", modifier = Modifier.weight(1f))
                    }
                }
            },
            confirmButton = {}
        )
    }

    // Add container dialog
    if (showAddContainer) {
        AlertDialog(
            onDismissRequest = { showAddContainer = false },
            title = { Text("新建容器") },
            text = { OutlinedTextField(newContainerName, { newContainerName = it }, label = { Text("容器名称") }, singleLine = true) },
            confirmButton = {
                Button(onClick = {
                    if (newContainerName.isNotBlank()) {
                        viewModel.addContainer(newContainerName)
                        showAddContainer = false
                        newContainerName = ""
                    }
                }) { Text("创建") }
            },
            dismissButton = { TextButton(onClick = { showAddContainer = false }) { Text("取消") } }
        )
    }
}

@Composable
private fun ContainerItem(container: Container, onClick: () -> Unit) {
    Card(Modifier.fillMaxWidth().clickable { onClick() }) {
        Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
            Icon(Icons.Default.Folder, null, tint = Color(0xFFFF9800))
            Spacer(Modifier.width(12.dp))
            Text(container.name ?: "未命名", modifier = Modifier.weight(1f), fontWeight = FontWeight.Medium)
            Icon(Icons.Default.ChevronRight, null, tint = Color.Gray)
        }
    }
}

@Composable
private fun ItemRow(item: Item, onClick: () -> Unit) {
    Card(Modifier.fillMaxWidth().clickable { onClick() }) {
        Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
            Icon(Icons.Default.Inventory, null, tint = Color(0xFF2196F3))
            Spacer(Modifier.width(12.dp))
            Column(Modifier.weight(1f)) {
                Text(item.name ?: "未命名", fontWeight = FontWeight.Medium)
                item.serial_number?.let { Text(it, fontSize = 12.sp, color = Color.Gray) }
            }
            Icon(Icons.Default.ChevronRight, null, tint = Color.Gray)
        }
    }
}
