package com.example.ops_android.ui.order

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
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.repository.OrderRepository
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 OrderFormUiState(
    val title: String = "",
    val remark: String = "",
    val link: String = "",
    val styleTags: String = "",
    val costs: List<Pair<String, String>> = listOf("" to ""),
    val isSubmitting: Boolean = false,
    val errorMessage: String? = null,
    val success: Boolean = false
)

class OrderFormViewModel(
    private val orderRepository: OrderRepository,
    private val editOrderId: Int? = null
) : ViewModel() {
    private val _uiState = MutableStateFlow(OrderFormUiState())
    val uiState: StateFlow<OrderFormUiState> = _uiState.asStateFlow()

    fun onTitleChange(v: String) { _uiState.value = _uiState.value.copy(title = v) }
    fun onRemarkChange(v: String) { _uiState.value = _uiState.value.copy(remark = v) }
    fun onLinkChange(v: String) { _uiState.value = _uiState.value.copy(link = v) }
    fun onStyleTagsChange(v: String) { _uiState.value = _uiState.value.copy(styleTags = v) }

    fun addCost() {
        _uiState.value = _uiState.value.copy(costs = _uiState.value.costs + ("" to ""))
    }

    fun updateCostAmount(index: Int, value: String) {
        val costs = _uiState.value.costs.toMutableList()
        costs[index] = costs[index].copy(first = value)
        _uiState.value = _uiState.value.copy(costs = costs)
    }

    fun updateCostCurrency(index: Int, value: String) {
        val costs = _uiState.value.costs.toMutableList()
        costs[index] = costs[index].copy(second = value)
        _uiState.value = _uiState.value.copy(costs = costs)
    }

    fun removeCost(index: Int) {
        val costs = _uiState.value.costs.toMutableList()
        if (costs.size > 1) {
            costs.removeAt(index)
            _uiState.value = _uiState.value.copy(costs = costs)
        }
    }

    fun submit() {
        val state = _uiState.value
        if (state.title.isBlank()) {
            _uiState.value = state.copy(errorMessage = "标题不能为空")
            return
        }

        val costList = state.costs
            .filter { it.first.isNotBlank() }
            .map { mapOf("amount" to it.first.toDoubleOrNull(), "currency" to it.second.ifBlank { "CNY" }) }

        val tags = state.styleTags
            .split(",", "，")
            .map { it.trim() }
            .filter { it.isNotBlank() }

        val data = mapOf(
            "title" to state.title,
            "remark" to state.remark,
            "link" to state.link,
            "style_tags" to tags,
            "costs" to costList
        )

        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isSubmitting = true, errorMessage = null)
            val result = if (editOrderId != null) {
                orderRepository.updateOrder(data + ("id" to editOrderId))
            } else {
                orderRepository.addOrder(data)
            }
            result.fold(
                onSuccess = { _uiState.value = _uiState.value.copy(isSubmitting = false, success = true) },
                onFailure = { e -> _uiState.value = _uiState.value.copy(isSubmitting = false, errorMessage = e.message) }
            )
        }
    }

    class Factory(
        private val orderRepository: OrderRepository,
        private val editOrderId: Int? = null
    ) : ViewModelProvider.Factory {
        @Suppress("UNCHECKED_CAST")
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return OrderFormViewModel(orderRepository, editOrderId) as T
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun OrderFormScreen(
    editOrderId: Int? = null,
    onBack: () -> Unit,
    onSaved: () -> Unit
) {
    val viewModel: OrderFormViewModel = viewModel(
        factory = OrderFormViewModel.Factory(LocalAppContainer.current.orderRepository, editOrderId)
    )
    val uiState by viewModel.uiState.collectAsState()

    LaunchedEffect(uiState.success) {
        if (uiState.success) onSaved()
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(if (editOrderId != 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 = Modifier.fillMaxSize().padding(padding).padding(16.dp).verticalScroll(rememberScrollState()),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            OutlinedTextField(value = uiState.title, onValueChange = viewModel::onTitleChange, label = { Text("标题 *") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
            OutlinedTextField(value = uiState.remark, onValueChange = viewModel::onRemarkChange, label = { Text("备注") }, modifier = Modifier.fillMaxWidth(), minLines = 2)
            OutlinedTextField(value = uiState.link, onValueChange = viewModel::onLinkChange, label = { Text("链接") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
            OutlinedTextField(value = uiState.styleTags, onValueChange = viewModel::onStyleTagsChange, label = { Text("款式标签（逗号分隔）") }, modifier = Modifier.fillMaxWidth(), singleLine = true)

            Text("费用明细", fontWeight = FontWeight.Bold, fontSize = 16.sp)

            uiState.costs.forEachIndexed { index, cost ->
                Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
                    OutlinedTextField(
                        value = cost.first, onValueChange = { viewModel.updateCostAmount(index, it) },
                        label = { Text("金额") }, modifier = Modifier.weight(1f), singleLine = true
                    )
                    OutlinedTextField(
                        value = cost.second, onValueChange = { viewModel.updateCostCurrency(index, it) },
                        label = { Text("币种") }, modifier = Modifier.weight(0.5f), singleLine = true,
                        placeholder = { Text("CNY") }
                    )
                    if (uiState.costs.size > 1) {
                        IconButton(onClick = { viewModel.removeCost(index) }) {
                            Text("✕", color = Color.Red)
                        }
                    }
                }
            }

            TextButton(onClick = { viewModel.addCost() }) { Text("+ 添加费用") }

            uiState.errorMessage?.let {
                Text(it, color = Color.Red, fontSize = 14.sp)
            }

            Button(
                onClick = { viewModel.submit() },
                modifier = Modifier.fillMaxWidth().height(48.dp),
                enabled = !uiState.isSubmitting
            ) {
                if (uiState.isSubmitting) CircularProgressIndicator(Modifier.size(20.dp), color = Color.White, strokeWidth = 2.dp)
                else Text("提交")
            }
        }
    }
}
