package com.example.ops_android.ui.search

import android.Manifest
import android.content.pm.PackageManager
import android.util.Size
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.foundation.background
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.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.QrCodeScanner
import androidx.compose.material.icons.filled.Search
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.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
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.data.model.PurchaseOrder
import com.example.ops_android.data.model.WorkOrder
import com.example.ops_android.ui.LocalAppContainer
import com.google.mlkit.vision.barcode.BarcodeScanner
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.barcode.common.Barcode
import com.google.mlkit.vision.common.InputImage

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchScreen(
    onOrderClick: (Int) -> Unit,
    onWorkOrderClick: (Int) -> Unit,
    onItemClick: (Int) -> Unit,
    onContainerClick: (Int) -> Unit,
    onBack: () -> Unit
) {
    val appContainer = LocalAppContainer.current
    val viewModel: SearchViewModel = viewModel(
        factory = SearchViewModel.Factory(appContainer.orderRepository, appContainer.workOrderRepository, appContainer.warehouseRepository)
    )
    val uiState by viewModel.uiState.collectAsState()
    var showScanner by remember { mutableStateOf(false) }
    val context = LocalContext.current
    var hasCameraPermission by remember { mutableStateOf(false) }

    val permissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
        hasCameraPermission = granted
        if (granted) showScanner = true
    }

    fun checkCameraAndScan() {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            hasCameraPermission = true
            showScanner = true
        } else {
            permissionLauncher.launch(Manifest.permission.CAMERA)
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("搜索") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, null, tint = Color.White)
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color(0xFF667EEA),
                    titleContentColor = Color.White
                )
            )
        }
    ) { padding ->
        if (showScanner) {
            BarcodeScannerView(
                onBarcodeScanned = { barcode ->
                    viewModel.onBarcodeScanned(barcode)
                    showScanner = false
                },
                onClose = { showScanner = false }
            )
            return@Scaffold
        }

        Column(modifier = Modifier.fillMaxSize().padding(padding)) {
            // Search bar
            Row(
                modifier = Modifier.fillMaxWidth().padding(12.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                OutlinedTextField(
                    value = uiState.query,
                    onValueChange = viewModel::onQueryChange,
                    modifier = Modifier.weight(1f),
                    placeholder = { Text("输入关键词搜索...", fontSize = 14.sp) },
                    singleLine = true,
                    trailingIcon = {
                        IconButton(onClick = { viewModel.search() }) {
                            Icon(Icons.Default.Search, "搜索")
                        }
                    },
                    shape = RoundedCornerShape(24.dp)
                )
                IconButton(onClick = { checkCameraAndScan() }) {
                    Icon(Icons.Default.QrCodeScanner, "扫码", tint = Color(0xFF667EEA))
                }
            }

            // Prefix hints
            Text(
                "前缀快捷搜索: po:采购单 wo:工单 item:物品 warehouse:容器",
                fontSize = 11.sp,
                color = Color.Gray,
                modifier = Modifier.padding(horizontal = 16.dp),
                textAlign = TextAlign.Center
            )

            // Category tabs
            PrimaryScrollableTabRow(
                selectedTabIndex = SearchCategory.entries.indexOf(uiState.category),
                modifier = Modifier.fillMaxWidth(),
                edgePadding = 8.dp
            ) {
                SearchCategory.entries.forEach { cat ->
                    Tab(
                        selected = uiState.category == cat,
                        onClick = { viewModel.selectCategory(cat); viewModel.clearResults() },
                        text = { Text(cat.label, fontSize = 13.sp) }
                    )
                }
            }

            if (uiState.isSearching) {
                Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                    CircularProgressIndicator()
                }
                return@Column
            }

            // Results
            LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
                val hasResults = uiState.orders.isNotEmpty() || uiState.workOrders.isNotEmpty() || uiState.items.isNotEmpty() || uiState.containers.isNotEmpty()

                if (!hasResults && uiState.query.isNotBlank()) {
                    item {
                        Box(Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) {
                            Text("未找到匹配结果", color = Color.Gray)
                        }
                    }
                }

                if (uiState.orders.isNotEmpty() && (uiState.category == SearchCategory.ALL || uiState.category == SearchCategory.ORDER)) {
                    item { CategoryHeader("采购订单") }
                    items(uiState.orders.take(5)) { order -> SearchOrderItem(order) { onOrderClick(order.id) } }
                }

                if (uiState.workOrders.isNotEmpty() && (uiState.category == SearchCategory.ALL || uiState.category == SearchCategory.WORK_ORDER)) {
                    item { CategoryHeader("工单") }
                    items(uiState.workOrders.take(5)) { wo -> SearchWorkOrderItem(wo) { onWorkOrderClick(wo.id) } }
                }

                if (uiState.items.isNotEmpty() && (uiState.category == SearchCategory.ALL || uiState.category == SearchCategory.ITEM)) {
                    item { CategoryHeader("物品") }
                    items(uiState.items.take(5)) { item -> SearchItemItem(item) { onItemClick(item.id) } }
                }

                if (uiState.containers.isNotEmpty() && (uiState.category == SearchCategory.ALL || uiState.category == SearchCategory.CONTAINER)) {
                    item { CategoryHeader("容器") }
                    items(uiState.containers.take(5)) { container -> SearchContainerItem(container) { onContainerClick(container.id) } }
                }
            }
        }
    }
}

@Composable
private fun CategoryHeader(title: String) {
    Text(title, fontWeight = FontWeight.Bold, fontSize = 14.sp, color = Color(0xFF667EEA), modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp))
}

@Composable
private fun SearchOrderItem(order: PurchaseOrder, onClick: () -> Unit) {
    Card(Modifier.fillMaxWidth().clickable { onClick() }) {
        Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
            Column(Modifier.weight(1f)) {
                Text(order.title ?: "无标题", fontWeight = FontWeight.Medium)
                order.remark?.takeIf { it.isNotBlank() }?.let { Text(it, fontSize = 12.sp, color = Color.Gray, maxLines = 1) }
            }
        }
    }
}

@Composable
private fun SearchWorkOrderItem(wo: WorkOrder, onClick: () -> Unit) {
    Card(Modifier.fillMaxWidth().clickable { onClick() }) {
        Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
            Column(Modifier.weight(1f)) {
                Text(wo.title ?: "无标题", fontWeight = FontWeight.Medium)
                wo.description?.takeIf { it.isNotBlank() }?.let { Text(it, fontSize = 12.sp, color = Color.Gray, maxLines = 1) }
            }
        }
    }
}

@Composable
private fun SearchItemItem(item: Item, onClick: () -> Unit) {
    Card(Modifier.fillMaxWidth().clickable { onClick() }) {
        Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
            Column(Modifier.weight(1f)) {
                Text(item.name ?: "未命名", fontWeight = FontWeight.Medium)
                item.serial_number?.let { Text("编号: $it", fontSize = 12.sp, color = Color.Gray) }
            }
        }
    }
}

@Composable
private fun SearchContainerItem(container: Container, onClick: () -> Unit) {
    Card(Modifier.fillMaxWidth().clickable { onClick() }) {
        Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
            Column(Modifier.weight(1f)) {
                Text(container.name ?: "未命名", fontWeight = FontWeight.Medium)
                container.barcode?.let { Text("条码: $it", fontSize = 12.sp, color = Color.Gray) }
            }
        }
    }
}

@Composable
fun BarcodeScannerView(
    onBarcodeScanned: (String) -> Unit,
    onClose: () -> Unit
) {
    val context = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current
    var hasScanned by remember { mutableStateOf(false) }

    Box(modifier = Modifier.fillMaxSize().background(Color.Black)) {
        AndroidView(
            factory = { ctx ->
                PreviewView(ctx).also { previewView ->
                    val cameraProviderFuture = ProcessCameraProvider.getInstance(ctx)
                    cameraProviderFuture.addListener({
                        val cameraProvider = cameraProviderFuture.get()
                        val preview = androidx.camera.core.Preview.Builder().build().also {
                            it.setSurfaceProvider(previewView.surfaceProvider)
                        }

                        val scanner = BarcodeScanning.getClient()
                        val imageAnalysis = ImageAnalysis.Builder()
                            .setTargetResolution(Size(1280, 720))
                            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
                            .build()
                        imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(ctx)) { imageProxy ->
                            if (!hasScanned) {
                                processImageProxy(scanner, imageProxy) { barcode ->
                                    hasScanned = true
                                    onBarcodeScanned(barcode)
                                }
                            } else {
                                imageProxy.close()
                            }
                        }

                        val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
                        try {
                            cameraProvider.unbindAll()
                            cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, preview, imageAnalysis)
                        } catch (e: Exception) { }
                    }, ContextCompat.getMainExecutor(ctx))
                }
            },
            modifier = Modifier.fillMaxSize()
        )

        Button(
            onClick = onClose,
            modifier = Modifier.align(Alignment.TopEnd).padding(16.dp)
        ) {
            Text("关闭")
        }
    }
}

private fun processImageProxy(scanner: BarcodeScanner, imageProxy: ImageProxy, onResult: (String) -> Unit) {
    val mediaImage = imageProxy.image
    if (mediaImage != null) {
        val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
        scanner.process(image)
            .addOnSuccessListener { barcodes ->
                for (barcode in barcodes) {
                    barcode.rawValue?.let { onResult(it) }
                }
            }
            .addOnCompleteListener { imageProxy.close() }
    } else {
        imageProxy.close()
    }
}
