package com.example.ops_android.ui.workorder

import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
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.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.FileProvider
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import com.example.ops_android.data.model.Customer
import com.example.ops_android.data.model.Item
import com.example.ops_android.ui.LocalAppContainer
import java.io.File

private fun createTempImageFile(context: android.content.Context): File {
    val dir = File(context.cacheDir, "photos")
    if (!dir.exists()) dir.mkdirs()
    return File(dir, "capture_${System.currentTimeMillis()}.jpg")
}

@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
fun WorkOrderFormScreen(editId: Int? = null, prefillItemId: Int? = null, onBack: () -> Unit, onSaved: () -> Unit) {
    val app = LocalAppContainer.current
    val context = LocalContext.current
    val vm: WorkOrderFormViewModel = viewModel(
        key = "wo_form_$editId",
        factory = WorkOrderFormViewModel.Factory(
            app.workOrderRepository, app.warehouseRepository, app.customerRepository,
            app.fileApi, app.sessionManager, context, editId, prefillItemId
        )
    )
    val s by vm.s.collectAsState()
    LaunchedEffect(s.success) { if (s.success) onSaved() }

    var showPhotoDialog by remember { mutableStateOf(false) }
    var cameraFileUri by remember { mutableStateOf<Uri?>(null) }

    val cameraLauncher = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { success ->
        val uri = cameraFileUri
        if (success && uri != null) vm.addPhoto(uri)
    }

    val galleryLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
        uri?.let { vm.addPhoto(it) }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(if (editId != null) "编辑工单" else "新建工单") },
                navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, null, tint = Color.White) } },
                colors = TopAppBarDefaults.topAppBarColors(containerColor = Color(0xFF667EEA), titleContentColor = Color.White)
            )
        }
    ) { padding ->
        Column(Modifier.fillMaxSize().padding(padding).padding(16.dp).verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(14.dp)) {
            // Title
            OutlinedTextField(s.title, vm::onTitle, label = { Text("标题 *") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
            OutlinedTextField(s.description, vm::onDesc, label = { Text("描述") }, modifier = Modifier.fillMaxWidth(), minLines = 3)

            // ── 关联物品 ──
            Text("关联物品", fontWeight = FontWeight.Bold, fontSize = 15.sp)

            // Selected item chips
            if (s.selectedItems.isNotEmpty()) {
                FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
                    s.selectedItems.forEach { item ->
                        InputChip(
                            selected = true,
                            onClick = { vm.removeItem(item) },
                            label = { Text(item.name ?: "?", fontSize = 12.sp) },
                            trailingIcon = { Icon(Icons.Default.Close, null, Modifier.size(16.dp)) }
                        )
                    }
                }
            }

            // Item search
            Column {
                OutlinedTextField(
                    s.itemSearchQuery, vm::onItemSearchQuery,
                    label = { Text("搜索物品") },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    leadingIcon = { Icon(Icons.Default.Search, null) }
                )
                if (s.isSearchingItems) {
                    LinearProgressIndicator(Modifier.fillMaxWidth().padding(vertical = 4.dp))
                }
                s.itemSearchResults.take(5).forEach { item ->
                    Surface(
                        modifier = Modifier.fillMaxWidth().clickable { vm.addItem(item) },
                        color = Color(0xFFF5F5F5)
                    ) {
                        Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
                            Icon(Icons.Default.Inventory, null, Modifier.size(20.dp), tint = Color(0xFF667EEA))
                            Spacer(Modifier.width(8.dp))
                            Column(Modifier.weight(1f)) {
                                Text(item.name ?: "", fontSize = 14.sp)
                                item.serial_number?.let { Text(it, fontSize = 12.sp, color = Color.Gray) }
                            }
                            Icon(Icons.Default.Add, null, Modifier.size(18.dp), tint = Color(0xFF4CAF50))
                        }
                    }
                }
            }

            // ── 关联客户 ──
            Text("关联客户", fontWeight = FontWeight.Bold, fontSize = 15.sp)

            // Selected customer chips
            if (s.selectedCustomers.isNotEmpty()) {
                FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
                    s.selectedCustomers.forEach { c ->
                        InputChip(
                            selected = true,
                            onClick = { vm.removeCustomer(c) },
                            label = { Text(c.name ?: "?", fontSize = 12.sp) },
                            trailingIcon = { Icon(Icons.Default.Close, null, Modifier.size(16.dp)) }
                        )
                    }
                }
            }

            // Customer search
            Column {
                OutlinedTextField(
                    s.customerSearchQuery, vm::onCustomerSearchQuery,
                    label = { Text("搜索客户") },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    leadingIcon = { Icon(Icons.Default.Search, null) }
                )
                if (s.isSearchingCustomers) {
                    LinearProgressIndicator(Modifier.fillMaxWidth().padding(vertical = 4.dp))
                }
                s.customerSearchResults.take(5).forEach { c ->
                    Surface(
                        modifier = Modifier.fillMaxWidth().clickable { vm.addCustomer(c) },
                        color = Color(0xFFF5F5F5)
                    ) {
                        Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
                            Icon(Icons.Default.Person, null, Modifier.size(20.dp), tint = Color(0xFF667EEA))
                            Spacer(Modifier.width(8.dp))
                            Column(Modifier.weight(1f)) {
                                Text(c.name ?: "", fontSize = 14.sp)
                                c.phone?.let { Text(it, fontSize = 12.sp, color = Color.Gray) }
                            }
                            Icon(Icons.Default.Add, null, Modifier.size(18.dp), tint = Color(0xFF4CAF50))
                        }
                    }
                }
            }

            // ── 图片 ──
            Text("照片", fontWeight = FontWeight.Bold, fontSize = 15.sp)
            FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                s.photos.forEach { photo ->
                    Box(Modifier.size(80.dp).clip(RoundedCornerShape(8.dp))) {
                        AsyncImage(
                            model = photo.uri,
                            contentDescription = null,
                            modifier = Modifier.fillMaxSize(),
                            contentScale = ContentScale.Crop
                        )
                        if (photo.isUploading) {
                            Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.4f)), contentAlignment = Alignment.Center) {
                                CircularProgressIndicator(Modifier.size(20.dp), color = Color.White, strokeWidth = 2.dp)
                            }
                        }
                        IconButton(
                            onClick = { vm.removePhoto(photo.uri) },
                            modifier = Modifier.align(Alignment.TopEnd).size(20.dp)
                        ) {
                            Icon(Icons.Default.Close, null, Modifier.size(14.dp), tint = Color.White)
                        }
                    }
                }
                IconButton(
                    onClick = { showPhotoDialog = true },
                    modifier = Modifier.size(80.dp).clip(RoundedCornerShape(8.dp)).background(Color(0xFFF0F0F0))
                ) {
                    Icon(Icons.Default.Add, null, Modifier.size(32.dp), tint = Color.Gray)
                }
            }

            // ── Error & Submit ──
            s.errorMessage?.let { Text(it, color = Color.Red, fontSize = 14.sp) }
            Button(
                onClick = { vm.submit() },
                modifier = Modifier.fillMaxWidth().height(48.dp),
                enabled = !s.isSubmitting && s.photos.none { it.isUploading }
            ) {
                if (s.isSubmitting) CircularProgressIndicator(Modifier.size(20.dp), color = Color.White, strokeWidth = 2.dp)
                else Text("提交")
            }
        }
    }

    if (showPhotoDialog) {
        AlertDialog(
            onDismissRequest = { showPhotoDialog = false },
            title = { Text("添加照片") },
            text = {
                Column {
                    TextButton(onClick = {
                        showPhotoDialog = false
                        val file = createTempImageFile(context)
                        val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
                        cameraFileUri = uri
                        cameraLauncher.launch(uri)
                    }, modifier = Modifier.fillMaxWidth()) {
                        Icon(Icons.Default.CameraAlt, null, Modifier.size(24.dp))
                        Spacer(Modifier.width(12.dp))
                        Text("拍照", modifier = Modifier.weight(1f))
                    }
                    TextButton(onClick = {
                        showPhotoDialog = false
                        galleryLauncher.launch("image/*")
                    }, modifier = Modifier.fillMaxWidth()) {
                        Icon(Icons.Default.PhotoLibrary, null, Modifier.size(24.dp))
                        Spacer(Modifier.width(12.dp))
                        Text("从相册选择", modifier = Modifier.weight(1f))
                    }
                }
            },
            confirmButton = {}
        )
    }
}
