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.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.*
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.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import com.example.ops_android.data.model.TabFileInfo
import com.example.ops_android.data.remote.api.ItemCommitDetail
import com.example.ops_android.data.remote.api.ItemResponse
import com.example.ops_android.data.remote.api.LinkedCustomerInfo
import com.example.ops_android.data.remote.api.LinkedWorkOrder
import com.example.ops_android.data.repository.WarehouseRepository
import com.example.ops_android.printer.PrintHelper
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 ItemDetailUiState(
    val itemResponse: ItemResponse? = null,
    val isLoading: Boolean = false,
    val isDeleting: Boolean = false,
    val errorMessage: String? = null,
    val deleted: Boolean = false
)

class ItemDetailViewModel(
    private val repo: WarehouseRepository,
    private val baseUrl: String,
    private val id: Int
) : ViewModel() {
    private val _s = MutableStateFlow(ItemDetailUiState())
    val s: StateFlow<ItemDetailUiState> = _s.asStateFlow()

    init { load() }

    fun load() {
        viewModelScope.launch {
            _s.value = _s.value.copy(isLoading = true)
            repo.getItem(id).fold(
                onSuccess = { _s.value = _s.value.copy(itemResponse = it, isLoading = false) },
                onFailure = { _s.value = _s.value.copy(isLoading = false, errorMessage = it.message) }
            )
        }
    }

    fun delete() {
        viewModelScope.launch {
            _s.value = _s.value.copy(isDeleting = true)
            repo.deleteItem(id).fold(
                onSuccess = { _s.value = _s.value.copy(isDeleting = false, deleted = true) },
                onFailure = { _s.value = _s.value.copy(isDeleting = false, errorMessage = it.message) }
            )
        }
    }

    fun move(newContainerId: Int?) {
        viewModelScope.launch {
            _s.value = _s.value.copy(isLoading = true)
            val targetId = newContainerId ?: 0 // 0 means unstored
            repo.moveItem(id, targetId).fold(
                onSuccess = { load() },
                onFailure = { _s.value = _s.value.copy(isLoading = false, errorMessage = it.message) }
            )
        }
    }

    fun photoUrl(hash: String?): String {
        if (hash.isNullOrBlank()) return ""
        val url = baseUrl.trimEnd('/')
        return "$url/files/get/$hash"
    }

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

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ItemDetailScreen(id: Int, onBack: () -> Unit, onCreateWorkOrder: (Int) -> Unit = {}, onWorkOrderClick: (Int) -> Unit = {}) {
    val app = LocalAppContainer.current
    val vm: ItemDetailViewModel = viewModel(
        key = "item_detail_$id",
        factory = ItemDetailViewModel.Factory(app.warehouseRepository, app.sessionManager.cachedBaseUrl, id)
    )
    val s by vm.s.collectAsState()
    val resp = s.itemResponse
    val item = resp?.item
    var tabIndex by remember { mutableIntStateOf(0) }
    var showDeleteDialog by remember { mutableStateOf(false) }
    var showMoveDialog by remember { mutableStateOf(false) }
    var previewPhotoUrl by remember { mutableStateOf<String?>(null) }

    LaunchedEffect(s.deleted) { if (s.deleted) onBack() }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("物品详情") },
                navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, null, tint = Color.White) } },
                actions = {
                    val scope = rememberCoroutineScope()
                    item?.let { itm ->
                        val printerManager = app.printerManager
                        if (printerManager != null) {
                            IconButton(onClick = {
                            scope.launch { PrintHelper.printItemLabel(printerManager, itm, labelWidthMm = app.sessionManager.cachedLabelWidthMm, labelHeightMm = app.sessionManager.cachedLabelHeightMm, blackMarkEnabled = app.sessionManager.cachedBlackMarkEnabled, unwindMm = app.sessionManager.cachedUnwindMm, printRetractMm = app.sessionManager.cachedPrintRetractMm) }
                            }) {
                                Icon(Icons.Default.Print, "打印", tint = Color.White)
                            }
                        }
                    }
                    IconButton(onClick = { onCreateWorkOrder(id) }) { Icon(Icons.Default.AddTask, "新建工单", tint = Color.White) }
                    if (resp?.canModifyItem == true) {
                        IconButton(onClick = { showMoveDialog = true }) { Icon(Icons.Default.OpenWith, "移动", tint = Color.White) }
                        IconButton(onClick = { showDeleteDialog = true }) { Icon(Icons.Default.Delete, "删除", 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 (item == null) { Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) { Text(s.errorMessage ?: "加载失败", color = Color.Red) }; return@Scaffold }

        Column(Modifier.fillMaxSize().padding(padding)) {
            LazyColumn(Modifier.weight(1f).padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
                // Basic info
                item {
                    Text(item.name ?: "未命名", fontWeight = FontWeight.Bold, fontSize = 20.sp)
                    item.serial_number?.let { Text(it, fontSize = 14.sp, color = Color.Gray) }
                    Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
                        Text("数量: ${item.quantity}", fontSize = 13.sp, color = Color.Gray)
                        resp.container_breadcrumb?.let { breadcrumb ->
                            if (breadcrumb.isNotBlank()) {
                                Text("位置: $breadcrumb", fontSize = 13.sp, color = Color(0xFF667EEA))
                            }
                        }
                    }
                }

                // Photos
                val photos = resp.photos
                if (!photos.isNullOrEmpty()) {
                    item {
                        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                            photos.forEach { photo ->
                                val url = vm.photoUrl(photo.sha256)
                                AsyncImage(
                                    model = url, contentDescription = null,
                                    modifier = Modifier.size(100.dp).clickable { previewPhotoUrl = url },
                                    contentScale = ContentScale.Crop
                                )
                            }
                        }
                    }
                }

                // Remark
                item.remark?.let { remark ->
                    if (remark.isNotBlank()) {
                        item { Text("备注: $remark", fontSize = 13.sp, color = Color.Gray) }
                    }
                }

                // Dates
                item {
                    Row(horizontalArrangement = Arrangement.spacedBy(24.dp)) {
                        item.created_at?.let { Text("创建: $it", fontSize = 12.sp, color = Color.Gray) }
                        item.updated_at?.let { Text("更新: $it", fontSize = 12.sp, color = Color.Gray) }
                    }
                }

                // Tabs
                item {
                    TabRow(selectedTabIndex = tabIndex) {
                        Tab(tabIndex == 0, { tabIndex = 0 }) { Text("关联工单") }
                        Tab(tabIndex == 1, { tabIndex = 1 }) { Text("关联客户") }
                        Tab(tabIndex == 2, { tabIndex = 2 }) { Text("移动历史") }
                    }
                }

                when (tabIndex) {
                    0 -> {
                        val workOrders = resp.work_orders
                        if (workOrders.isNullOrEmpty()) {
                            item { Text("暂无关联工单", Modifier.padding(16.dp), color = Color.Gray) }
                    } else {
                        items(workOrders) { wo ->
                            WorkOrderRow(wo) { onWorkOrderClick(wo.id) }
                        }
                        }
                    }
                    1 -> {
                        val customers = resp.customers
                        if (customers.isNullOrEmpty()) {
                            item { Text("暂无关联客户", Modifier.padding(16.dp), color = Color.Gray) }
                        } else {
                            items(customers) { c ->
                                CustomerRow(c)
                            }
                        }
                    }
                    2 -> {
                        val commits = resp.commits
                        if (commits.isNullOrEmpty()) {
                            item { Text("暂无移动记录", Modifier.padding(16.dp), color = Color.Gray) }
                        } else {
                            items(commits) { commit ->
                                Card(Modifier.fillMaxWidth()) {
                                    Column(Modifier.padding(12.dp)) {
                                        Text(commit.CreatedAt ?: "", fontSize = 12.sp, color = Color.Gray)
                                        Row(verticalAlignment = Alignment.CenterVertically) {
                                            Text(commit.OldContainerBreadcrumb ?: "未入库", fontSize = 13.sp)
                                            Icon(Icons.Default.ArrowForward, null, Modifier.size(16.dp), tint = Color.Gray)
                                            Text(commit.NewContainerBreadcrumb ?: "未入库", fontSize = 13.sp, color = Color(0xFF667EEA))
                                        }
                                        commit.Remark?.let { if (it.isNotBlank()) Text(it, fontSize = 12.sp, color = Color.Gray) }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    if (showDeleteDialog) {
        AlertDialog(
            onDismissRequest = { showDeleteDialog = false },
            title = { Text("删除物品") },
            text = { Text("确定要删除「${item?.name}」吗？此操作不可撤销。") },
            confirmButton = {
                TextButton(onClick = { showDeleteDialog = false; vm.delete() }) {
                    Text("确定", color = Color(0xFFF44336))
                }
            },
            dismissButton = { TextButton(onClick = { showDeleteDialog = false }) { Text("取消") } }
        )
    }

    if (showMoveDialog) {
        MoveDialog(
            currentBreadcrumb = resp?.container_breadcrumb ?: "未入库",
            onDismiss = { showMoveDialog = false },
            onMove = { newContainerId ->
                showMoveDialog = false
                vm.move(newContainerId)
            }
        )
    }

    if (previewPhotoUrl != null) {
        Dialog(onDismissRequest = { previewPhotoUrl = null }) {
            Card(Modifier.fillMaxWidth()) {
                AsyncImage(model = previewPhotoUrl!!, contentDescription = null, modifier = Modifier.fillMaxWidth(), contentScale = ContentScale.FillWidth)
            }
        }
    }
}

@Composable
private fun WorkOrderRow(wo: LinkedWorkOrder, onClick: () -> Unit = {}) {
    val statusColors = mapOf("pending" to Color(0xFFFF9800), "checked" to Color(0xFF2196F3), "parts_ordered" to Color(0xFF9C27B0), "repaired" to Color(0xFF4CAF50), "returned" to Color(0xFF4CAF50), "unrepairable" to Color(0xFFF44336))
    val statusLabels = mapOf("pending" to "待处理", "checked" to "已检查", "parts_ordered" to "待配件", "repaired" to "已修复", "returned" to "已返还", "unrepairable" to "不可修")
    Card(Modifier.fillMaxWidth().clickable { onClick() }) {
        Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
            Column(Modifier.weight(1f)) {
                Text(wo.title ?: "", fontWeight = FontWeight.Medium)
            }
            Surface(shape = MaterialTheme.shapes.small, color = statusColors[wo.status]?.copy(alpha = 0.15f) ?: Color.Gray) {
                Text(statusLabels[wo.status] ?: wo.status ?: "", modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), fontSize = 11.sp, color = statusColors[wo.status] ?: Color.Gray)
            }
        }
    }
}

@Composable
private fun CustomerRow(c: LinkedCustomerInfo) {
    Card(Modifier.fillMaxWidth()) {
        Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
            Icon(Icons.Default.Person, null, Modifier.size(24.dp), tint = Color(0xFF667EEA))
            Spacer(Modifier.width(8.dp))
            Column {
                val name = listOfNotNull(c.last_name, c.first_name).joinToString(" ").ifEmpty { "未命名" }
                Text(name, fontWeight = FontWeight.Medium)
                c.primary_phone?.let { Text(it, fontSize = 12.sp, color = Color.Gray) }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun MoveDialog(currentBreadcrumb: String, onDismiss: () -> Unit, onMove: (Int?) -> Unit) {
    var search by remember { mutableStateOf("") }
    var results by remember { mutableStateOf<List<com.example.ops_android.data.model.Container>>(emptyList()) }
    var selectedId by remember { mutableStateOf<Int?>(null) }
    val app = LocalAppContainer.current

    fun doSearch() {
        kotlinx.coroutines.MainScope().launch {
            app.warehouseRepository.listContainer().fold(
                onSuccess = { containers ->
                    results = if (search.isBlank()) containers.take(10)
                    else containers.filter { (it.name ?: "").contains(search, ignoreCase = true) }.take(10)
                },
                onFailure = { }
            )
        }
    }

    LaunchedEffect(Unit) { doSearch() }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("移动物品") },
        text = {
            Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                Text("当前位置: $currentBreadcrumb", fontSize = 13.sp, color = Color.Gray)
                OutlinedTextField(search, { search = it; doSearch() }, label = { Text("搜索目标容器") }, singleLine = true, modifier = Modifier.fillMaxWidth())
                TextButton(onClick = { selectedId = null }) {
                    Text("→ 未入库（取出物品）", color = Color(0xFFFF9800))
                }
                results.take(5).forEach { c ->
                    Surface(
                        Modifier.fillMaxWidth().clickable { selectedId = c.id },
                        color = if (selectedId == c.id) Color(0xFFE8EAF6) else Color.Transparent
                    ) {
                        Text(c.name ?: "?", Modifier.padding(8.dp))
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = { onMove(selectedId) }) { Text("确认移动") }
        },
        dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } }
    )
}
