package com.example.ops_android.ui.customer

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.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.automirrored.filled.ArrowBack
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.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.ops_android.data.model.Customer
import com.example.ops_android.data.repository.CustomerRepository
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 CustomerListUiState(
    val customers: List<Customer> = emptyList(), val isLoading: Boolean = false, val errorMessage: String? = null,
    val showForm: Boolean = false, val editingCustomer: Customer? = null,
    val formName: String = "", val formPhone: String = "", val formEmail: String = "", val formAddress: String = "", val formRemark: String = "",
    val isSubmitting: Boolean = false
)

class CustomerListViewModel(private val repo: CustomerRepository) : ViewModel() {
    private val _s = MutableStateFlow(CustomerListUiState()); val s: StateFlow<CustomerListUiState> = _s.asStateFlow()
    init { load() }
    private fun load() { viewModelScope.launch { _s.value = _s.value.copy(isLoading = true); repo.list().fold(onSuccess = { _s.value = _s.value.copy(customers = it, isLoading = false) }, onFailure = { _s.value = _s.value.copy(isLoading = false, errorMessage = it.message) }) } }

    fun showAddForm() { _s.value = _s.value.copy(showForm = true, editingCustomer = null, formName = "", formPhone = "", formEmail = "", formAddress = "", formRemark = "") }
    fun showEditForm(c: Customer) { _s.value = _s.value.copy(showForm = true, editingCustomer = c, formName = c.name ?: "", formPhone = c.phone ?: "", formEmail = c.email ?: "", formAddress = c.address ?: "", formRemark = c.remark ?: "") }
    fun dismissForm() { _s.value = _s.value.copy(showForm = false) }
    fun onFormName(v: String) { _s.value = _s.value.copy(formName = v) }
    fun onFormPhone(v: String) { _s.value = _s.value.copy(formPhone = v) }
    fun onFormEmail(v: String) { _s.value = _s.value.copy(formEmail = v) }
    fun onFormAddress(v: String) { _s.value = _s.value.copy(formAddress = v) }
    fun onFormRemark(v: String) { _s.value = _s.value.copy(formRemark = v) }

    fun submitForm() {
        val st = _s.value
        if (st.formName.isBlank()) { _s.value = st.copy(errorMessage = "名称不能为空"); return }
        val data = mapOf("name" to st.formName, "phone" to st.formPhone, "email" to st.formEmail, "address" to st.formAddress, "remark" to st.formRemark)
        viewModelScope.launch {
            _s.value = _s.value.copy(isSubmitting = true)
            val r = if (st.editingCustomer != null) repo.update(data + ("id" to st.editingCustomer.id)) else repo.add(data)
            r.fold(onSuccess = { _s.value = _s.value.copy(isSubmitting = false, showForm = false); load() }, onFailure = { _s.value = _s.value.copy(isSubmitting = false, errorMessage = it.message) })
        }
    }

    fun deleteCustomer(id: Int) { viewModelScope.launch { repo.delete(id).fold(onSuccess = { load() }, onFailure = { _s.value = _s.value.copy(errorMessage = it.message) }) } }

    class Factory(private val repo: CustomerRepository) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(c: Class<T>): T = CustomerListViewModel(repo) as T }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CustomerListScreen(onBack: () -> Unit) {
    val vm: CustomerListViewModel = viewModel(factory = CustomerListViewModel.Factory(LocalAppContainer.current.customerRepository))
    val s by vm.s.collectAsState()

    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)) },
        floatingActionButton = { FloatingActionButton(onClick = { vm.showAddForm() }, containerColor = Color(0xFF667EEA)) { Icon(Icons.Default.Add, "添加", tint = Color.White) } }
    ) { padding ->
        if (s.isLoading) { Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) { CircularProgressIndicator() }; return@Scaffold }

        LazyColumn(Modifier.fillMaxSize().padding(padding), contentPadding = PaddingValues(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
            items(s.customers, key = { it.id }) { c ->
                Card(Modifier.fillMaxWidth().clickable { vm.showEditForm(c) }) {
                    Column(Modifier.padding(12.dp)) {
                        Text(c.name ?: "未命名", fontWeight = FontWeight.Medium)
                        c.phone?.takeIf { it.isNotBlank() }?.let { Text("电话: $it", fontSize = 13.sp, color = Color.Gray) }
                        c.email?.takeIf { it.isNotBlank() }?.let { Text("邮箱: $it", fontSize = 13.sp, color = Color.Gray) }
                    }
                }
            }
        }
    }

    if (s.showForm) AlertDialog(
        onDismissRequest = { vm.dismissForm() },
        title = { Text(if (s.editingCustomer != null) "编辑客户" else "添加客户") },
        text = {
            Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                OutlinedTextField(s.formName, vm::onFormName, label = { Text("名称 *") }, singleLine = true, modifier = Modifier.fillMaxWidth())
                OutlinedTextField(s.formPhone, vm::onFormPhone, label = { Text("电话") }, singleLine = true, modifier = Modifier.fillMaxWidth())
                OutlinedTextField(s.formEmail, vm::onFormEmail, label = { Text("邮箱") }, singleLine = true, modifier = Modifier.fillMaxWidth())
                OutlinedTextField(s.formAddress, vm::onFormAddress, label = { Text("地址") }, singleLine = true, modifier = Modifier.fillMaxWidth())
                OutlinedTextField(s.formRemark, vm::onFormRemark, label = { Text("备注") }, minLines = 2, modifier = Modifier.fillMaxWidth())
            }
        },
        confirmButton = {
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                if (s.editingCustomer != null) {
                    TextButton(onClick = { vm.deleteCustomer(s.editingCustomer!!.id) }) { Text("删除", color = Color.Red) }
                }
                Button(onClick = { vm.submitForm() }, enabled = !s.isSubmitting) { Text("保存") }
            }
        },
        dismissButton = { TextButton(onClick = { vm.dismissForm() }) { Text("取消") } }
    )
}
