import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.za.base.theme.bgColor
import com.za.base.theme.headBgColor
import com.za.base.view.HeadView
import com.za.ext.finish
import com.za.ui.servicing.order_confirm.modify_money.ModifyMoneyViewModel


@Composable
fun ModifyMoneyScreen(userOrderId : Int, taskId : Int, vm : ModifyMoneyViewModel = viewModel()) {

	val uiState = vm.uiState.collectAsStateWithLifecycle()
	val context = LocalContext.current
	LaunchedEffect(Unit) {
		vm.dispatch(ModifyMoneyViewModel.Action.Init(userOrderId, taskId))
	}

	if (uiState.value.saveSuccess == true) {
		context.finish()
	}

	Scaffold(containerColor = bgColor, topBar = {
		HeadView(title = "修改金额", onBack = { context.finish() })
	}) {
		Column(modifier = Modifier
			.fillMaxSize()
			.padding(it)
			.padding(20.dp)) {
			Spacer(modifier = Modifier.height(12.dp))
			if (uiState.value.paymentInfoBean?.payItem == 1) {
				MoneyInputField(value = "${uiState.value.unitPrice ?: "0"}",
					onValueChange = { vm.updateState(uiState.value.copy(unitPrice = it.toFloat())) },
					label = "单价",
					suffix = "元/公里",
					hint = uiState.value.paymentInfoBean?.unitPrice?.toString() ?: "0",
					enabled = false)
			} else {
				MoneyInputField(value = "${uiState.value.unitPrice ?: "0"}",
					onValueChange = { vm.updateState(uiState.value.copy(unitPrice = it.toFloat())) },
					label = "超限单价",
					suffix = "元/公里",
					hint = uiState.value.paymentInfoBean?.unitPrice?.toString() ?: "0",
					enabled = false)
			}

			Spacer(modifier = Modifier.height(12.dp))

			MoneyInputField(value = uiState.value.mileageText ?: "",
				onValueChange = {
					vm.dispatch(ModifyMoneyViewModel.Action.ChangeMileage((it)))
				},
				label = "全程公里数,免拖${uiState.value.paymentInfoBean?.limitedMileage ?: "_"}公里,最低${uiState.value.paymentInfoBean?.originalMileage ?: "_"}公里",
				hint = uiState.value.mileageText ?: "0",
				suffix = "公里")

			Spacer(modifier = Modifier.height(12.dp))

			MoneyInputField(value = "${uiState.value.calculateAmount ?: 0}",
				onValueChange = { },
				label = "计算金额",
				suffix = "元",
				hint = uiState.value.paymentInfoBean?.calculateAmount?.toString() ?: "0",
				enabled = false)

			Spacer(modifier = Modifier.height(12.dp))

			//超限类型只允许修改公里数，额外费用和超限单价不允许修改
			MoneyInputField(value = uiState.value.adjustAmountText ?: "",
				onValueChange = {
					vm.dispatch(ModifyMoneyViewModel.Action.ChangeAdjustAmount(it))
				},
				label = "额外费用",
				hint = uiState.value.paymentInfoBean?.adjustAmount?.toString() ?: "0",
				suffix = "元",
				enabled = uiState.value.paymentInfoBean?.payItem == 1)

			Spacer(modifier = Modifier.height(2.dp))

			OutlinedTextField(value = uiState.value.adjustRemark,
				onValueChange = { vm.updateState(uiState.value.copy(adjustRemark = it)) },
				label = { Text("调整原因") },
				placeholder = { Text("请输入调整原因", color = Color(0xFF666666)) },
				modifier = Modifier
					.fillMaxWidth()
					.height(80.dp),
				enabled = true)

			Spacer(modifier = Modifier.weight(1f))

			// 替换原来的 Row 为新的底部布局
			Surface(modifier = Modifier
				.fillMaxWidth()
				.padding(bottom = 16.dp),
				tonalElevation = 8.dp,
				shadowElevation = 8.dp,
				color = Color.White,
				shape = RoundedCornerShape(16.dp)) {
				Row(modifier = Modifier
					.fillMaxWidth()
					.padding(horizontal = 20.dp, vertical = 16.dp),
					horizontalArrangement = Arrangement.SpaceBetween,
					verticalAlignment = Alignment.CenterVertically) {
					Column {
						Text(text = "总金额",
							style = MaterialTheme.typography.bodyMedium,
							color = MaterialTheme.colorScheme.onSurfaceVariant)
						Text(text = "¥ ${uiState.value.totalMoney ?: 0}",
							style = MaterialTheme.typography.headlineMedium,
							color = headBgColor,
							fontWeight = FontWeight.Bold)
					}

					Button(onClick = { vm.dispatch(ModifyMoneyViewModel.Action.Save) },
						modifier = Modifier
							.height(48.dp)
							.width(120.dp),
						shape = RoundedCornerShape(24.dp),
						colors = ButtonDefaults.buttonColors(containerColor = headBgColor)) {
						Text("保存",
							style = MaterialTheme.typography.bodyLarge,
							fontWeight = FontWeight.Medium)
					}
				}
			}
		}
	}
}

@Composable
private fun MoneyInputField(value : String,
	onValueChange : (String) -> Unit,
	label : String,
	suffix : String,
	hint : String,
	keyboardType : KeyboardType = KeyboardType.Decimal,
	enabled : Boolean = true) {
	val secondaryTextColor = Color(0xFF666666)

	OutlinedTextField(value = value,
		placeholder = { Text(hint, color = secondaryTextColor) },
		onValueChange = { onValueChange(it) },
		label = { Text(label, color = secondaryTextColor) },
		modifier = Modifier
			.fillMaxWidth()
			.padding(vertical = 4.dp),
		enabled = enabled,
		keyboardOptions = KeyboardOptions(keyboardType = keyboardType),
		trailingIcon = {
			Text(suffix, modifier = Modifier.padding(end = 12.dp), color = secondaryTextColor)
		},
		colors = OutlinedTextFieldDefaults.colors(focusedBorderColor = headBgColor,
			unfocusedBorderColor = Color(0xFFE0E0E0),
			focusedLabelColor = headBgColor,
			unfocusedLabelColor = secondaryTextColor,
			cursorColor = headBgColor),
		shape = RoundedCornerShape(8.dp))
}

@Preview
@Composable
private fun ModifyMoneyPre() {
	ModifyMoneyScreen(userOrderId = 0, taskId = 0)
}