package com.za.ui.new_order

import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.Looper
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
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.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.BottomSheetScaffold
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.SheetValue
import androidx.compose.material3.Text
import androidx.compose.material3.rememberBottomSheetScaffoldState
import androidx.compose.material3.rememberStandardBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
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.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import com.amap.api.location.AMapLocationClient
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapView
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.PolylineOptions
import com.za.base.BaseActivity
import com.za.base.theme.headBgColor
import com.za.base.view.CommonDialog
import com.za.base.view.HeadViewNotBack
import com.za.bean.JpushBean
import com.za.call.CallLogManager
import com.za.call.ContactRecordBean
import com.za.common.GlobalData
import com.za.common.log.LogUtil
import com.za.common.util.ImageUtil
import com.za.ext.callPhone
import com.za.ext.copy
import com.za.ext.finish
import com.za.servicing.R
import com.za.ui.servicing.in_servicing_setting.OrderTaskNotesDialog

class NewOrderActivity : BaseActivity() {

	@Composable
	override fun ContentView() {
		val jpushBean = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
			intent.getSerializableExtra("jpushBean", JpushBean::class.java)
		} else {
			intent.getSerializableExtra("jpushBean")
		}
		GlobalData.isHandlerNewOrder = false
		AcceptOrderScreen(jpushBean = jpushBean as JpushBean)
	}

	override fun onStop() {
		super.onStop()
		GlobalData.isHandlerNewOrder = true
	}

	companion object {
		fun goNewOrderActivity(context : Context, jpushBean : JpushBean) {
			val intent = Intent(context, NewOrderActivity::class.java)
			intent.putExtra("jpushBean", jpushBean)
			context.startActivity(intent)
		}
	}
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun AcceptOrderScreen(jpushBean : JpushBean?, vm : NewOrderVm = viewModel()) {
	val context = LocalContext.current
	val uiState = vm.uiState.collectAsStateWithLifecycle()
	val mapView = remember { MapView(context) }

	// 将状态提升到 Composable 层级
	val lastRoutePoints = remember { mutableStateOf<List<LatLng>?>(null) }
	val lastMarkers = remember { mutableStateOf<ArrayList<MarkerOptions>?>(null) }
	val lastCurrentLocation = remember { mutableStateOf<LatLng?>(null) }

	val bottomSheetState = rememberStandardBottomSheetState(initialValue = SheetValue.Expanded)
	val scaffoldState = rememberBottomSheetScaffoldState(bottomSheetState = bottomSheetState)

	LaunchedEffect(key1 = Unit) {
		vm.dispatch(NewOrderVm.Action.Init(jpushBean as JpushBean))
	}

	val lifecycleOwner = LocalLifecycleOwner.current
	DisposableEffect(key1 = lifecycleOwner) {
		val observer = LifecycleEventObserver { _, event ->
			try {
				when (event) {
					Lifecycle.Event.ON_CREATE -> mapView.onCreate(null)
					Lifecycle.Event.ON_RESUME -> mapView.onResume()
					Lifecycle.Event.ON_PAUSE -> mapView.onPause()
					Lifecycle.Event.ON_DESTROY -> {
						mapView.onDestroy()
						vm.dispatch(NewOrderVm.Action.UpdateState(uiState.value.copy(remainingTime = 0)))
					}

					else -> {}
				}
			} catch (e : Exception) {
				LogUtil.print("LifecycleObserver", "生命周期事件处理异常: ${e.message}")
			}
		}

		lifecycleOwner.lifecycle.addObserver(observer)
		onDispose {
			try {
				lifecycleOwner.lifecycle.removeObserver(observer)
				vm.dispatch(NewOrderVm.Action.UpdateState(uiState.value.copy(remainingTime = 0)))
			} catch (e : Exception) {
				LogUtil.print("DisposableEffect", "清理资源异常: ${e.message}")
			}
		}
	}

	if (uiState.value.showCallPhoneDialog == true) {
		CommonDialog(cancelText = "取消",
			confirmText = "确定",
			title = "是否联系客户？",
			cancelEnable = true,
			cancel = {
				vm.dispatch(NewOrderVm.Action.UpdateState(uiState.value.copy(showCallPhoneDialog = false)))
				context.finish()
			},
			dismiss = {
				vm.dispatch(NewOrderVm.Action.UpdateState(uiState.value.copy(showCallPhoneDialog = false)))
			},
			confirm = {
				vm.dispatch(NewOrderVm.Action.UpdateState(uiState.value.copy(showCallPhoneDialog = false)))
				context.callPhone(uiState.value.jpushBean?.customerPhone)
				CallLogManager.phoneCallContactBean =
					ContactRecordBean(taskId = uiState.value.jpushBean?.taskId,
						taskCode = uiState.value.jpushBean?.taskCode,
						phone = uiState.value.jpushBean?.customerPhone)
				context.finish()
			})
	}

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

	// 添加超时对话框
	if (uiState.value.showTimeoutDialog) {
		CommonDialog(cancelText = "关闭",
			confirmText = "确定",
			title = "订单已超时",
			message = "当前订单已超时，请等待新的订单",
			cancelEnable = false,
			dismiss = {
				vm.dispatch(NewOrderVm.Action.UpdateState(uiState.value.copy(showTimeoutDialog = false)))
				context.finish()
			},
			confirm = {
				vm.dispatch(NewOrderVm.Action.UpdateState(uiState.value.copy(showTimeoutDialog = false)))
				context.finish()
			})
	}

	if (uiState.value.acceptOrderDialog == true) {
		CommonDialog(title = "请确认是否接受该任务！",
			confirmText = "确认接单",
			cancelText = "再想想",
			cancelEnable = false,
			confirm = {
				vm.updateState(uiState.value.copy(acceptOrderDialog = false))
				vm.dispatch(NewOrderVm.Action.ShowTaskNotes)
			},
			cancel = {},
			dismiss = {})
	}

	if (uiState.value.showTaskNotesDialog == true) {
		OrderTaskNotesDialog(uiState.value.taskNotesBean,
			uiState.value.jpushBean?.hasReplaceBatteryCapable == 2,
			dismiss = {},
			confirm = {
				vm.dispatch(NewOrderVm.Action.AcceptOrder)
			})
	}

	BottomSheetScaffold(scaffoldState = scaffoldState,
		topBar = { HeadViewNotBack(title = "新订单") },
		sheetContent = {
			Column(modifier = Modifier
				.fillMaxWidth()
				.wrapContentHeight()
				.background(Color.White)
				.verticalScroll(rememberScrollState())) { // 滑动指示器
				Box(modifier = Modifier
					.fillMaxWidth()
					.padding(vertical = 8.dp)
					.background(Color.White), contentAlignment = Alignment.Center) {
					Box(modifier = Modifier
						.width(32.dp)
						.height(4.dp)
						.background(color = Color(0xFFE0E0E0), shape = RoundedCornerShape(2.dp)))
				}

				// 滑动指示器和订单类型行
				Row(modifier = Modifier
					.fillMaxWidth()
					.padding(horizontal = 16.dp, vertical = 12.dp),
					horizontalArrangement = Arrangement.SpaceBetween,
					verticalAlignment = Alignment.CenterVertically) {
					Text(text = uiState.value.jpushBean?.serviceTypeName ?: "",
						fontSize = 18.sp,
						fontWeight = FontWeight.Bold,
						color = Color.Black)

					// 修改倒计时显示
					Text(text = if (uiState.value.isTimeout) "已超时" else "${uiState.value.remainingTime}S",
						color = Color(0xFFFF4D4F),
						fontSize = 20.sp,
						fontWeight = FontWeight.Bold)
				}

				// 添加距离和时间信息
				// 距离和时间信息
				Row(modifier = Modifier
					.fillMaxWidth()
					.padding(horizontal = 16.dp, vertical = 12.dp),
					horizontalArrangement = Arrangement.SpaceBetween,
					verticalAlignment = Alignment.CenterVertically) {
					Text(text = if (uiState.value.estimatedArrivalTime.isNotEmpty()) "预计到达: ${uiState.value.estimatedArrivalTime}"
					else "计算中...", color = Color(0xFF666666), fontSize = 14.sp)

					Text(text = if (uiState.value.remainingDistance > 0) "距离救援地: %.1fkm".format(
						uiState.value.remainingDistance / 1000f)
					else "计算中...", color = Color(0xFFFF4D4F), fontSize = 14.sp)
				}

				HorizontalDivider(modifier = Modifier
					.fillMaxWidth()
					.alpha(0.1f))

				// 订单信息
				Column(modifier = Modifier
					.fillMaxWidth()
					.padding(horizontal = 16.dp, vertical = 12.dp)) { // 订单标签
					Text(text = uiState.value.jpushBean?.serviceTypeName ?: "",
						fontSize = 18.sp,
						fontWeight = FontWeight.Bold,
						color = Color.Black)

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

					// 订单标签
					Row(verticalAlignment = Alignment.CenterVertically,
						horizontalArrangement = Arrangement.spacedBy(8.dp)) {
						Box(modifier = Modifier
							.background(Color(0xFF9BA1B2), RoundedCornerShape(4.dp))
							.padding(horizontal = 6.dp, vertical = 2.dp)) {
							Text(text = "月结".takeIf { uiState.value.jpushBean?.settleType == 1 }
								?: "现金", color = Color.White, fontSize = 12.sp)
						}

						Text(text = uiState.value.jpushBean?.orderSource ?: "",
							color = Color.Black,
							fontSize = 12.sp)

						Text(text = uiState.value.jpushBean?.addressProperty ?: "",
							color = Color(0xFFFD8205),
							fontSize = 12.sp,
							fontWeight = FontWeight.Medium)
					}

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

					// 订单号
					Row(verticalAlignment = Alignment.CenterVertically,
						modifier = Modifier.clickable {
							uiState.value.jpushBean?.taskCode?.copy(context)
						}) {
						Text(text = "单号", color = Color(0xFF999999), fontSize = 13.sp)

						Spacer(modifier = Modifier.width(8.dp))

						Text(text = uiState.value.jpushBean?.taskCode ?: "",
							color = Color(0xFF666666),
							fontSize = 14.sp)

						Spacer(modifier = Modifier.width(8.dp))

						AsyncImage(model = R.drawable.sv_copy,
							contentDescription = "copy",
							modifier = Modifier.size(16.dp))
					}

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

					// 地址信息
					Column(verticalArrangement = Arrangement.spacedBy(16.dp)) { // 救援地
						Row(verticalAlignment = Alignment.Top,
							modifier = Modifier.clickable { // 点击救援地时移动地图到救援位置
								uiState.value.jpushBean?.let { order ->
									if (order.lat != null && order.lat != 0.0 && order.lng != null && order.lng != 0.0) {
										mapView.map.animateCamera(CameraUpdateFactory.newLatLngZoom(
											LatLng(order.lat !!, order.lng !!),
											16f))
									}
								}
							}) {
							AsyncImage(model = R.drawable.sv_rescuing,
								contentDescription = "rescue",
								modifier = Modifier.size(16.dp))

							Spacer(modifier = Modifier.width(8.dp))

							Text(text = uiState.value.jpushBean?.address ?: "",
								color = Color.Black,
								fontSize = 15.sp,
								fontWeight = FontWeight.Medium)
						}

						// 目的地
						if (! uiState.value.jpushBean?.distAddress.isNullOrBlank()) {
							Row(verticalAlignment = Alignment.Top,
								modifier = Modifier.clickable { // 点击目的地时移动地图到目的地位置
									uiState.value.jpushBean?.let { order ->
										if (order.distLat != null && order.distLat != 0.0 && order.distLng != null && order.distLng != 0.0) {
											mapView.map.animateCamera(CameraUpdateFactory.newLatLngZoom(
												LatLng(order.distLat !!, order.distLng !!),
												16f))
										}
									}
								}) {
								AsyncImage(model = R.drawable.sv_dist,
									contentDescription = "destination",
									modifier = Modifier.size(16.dp))

								Spacer(modifier = Modifier.width(8.dp))

								Text(text = uiState.value.jpushBean?.distAddress ?: "",
									color = Color.Black,
									fontSize = 15.sp,
									fontWeight = FontWeight.Medium)
							}
						}
					}

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

					// 修改按钮状态
					Row(modifier = Modifier
						.fillMaxWidth()
						.padding(horizontal = 16.dp, vertical = 16.dp),
						horizontalArrangement = Arrangement.spacedBy(12.dp)) { // 拒单按钮
						Button(onClick = { vm.dispatch(NewOrderVm.Action.RefuseOrder) },
							modifier = Modifier
								.weight(1f)
								.height(44.dp),
							colors = ButtonDefaults.buttonColors(containerColor = Color.White,
								contentColor = Color(0xFF666666)),
							border = BorderStroke(1.dp, Color(0xFFE5E5E5)),
							shape = RoundedCornerShape(8.dp)) {
							Text(text = "拒绝", fontSize = 16.sp, fontWeight = FontWeight.Medium)
						}

						// 接单按钮
						Button(onClick = { vm.dispatch(NewOrderVm.Action.ShowTaskNotes) },
							modifier = Modifier
								.weight(1f)
								.height(44.dp),
							colors = ButtonDefaults.buttonColors(containerColor = headBgColor),
							shape = RoundedCornerShape(8.dp)) {
							Text(text = "接单",
								color = Color.White,
								fontSize = 16.sp,
								fontWeight = FontWeight.Medium)
						}
					}
				}
			}
		},
		sheetPeekHeight = 180.dp,
		sheetShape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
		sheetContainerColor = Color.White,
		sheetShadowElevation = 8.dp,
		sheetDragHandle = null,
		sheetSwipeEnabled = true) { paddingValues ->
		Box(modifier = Modifier
			.fillMaxSize()
			.padding(paddingValues)) {
			AndroidView(modifier = Modifier.fillMaxSize(), factory = {
				AMapLocationClient.updatePrivacyShow(context, true, true)
				AMapLocationClient.updatePrivacyAgree(context, true)
				mapView.apply {
					map.apply {
						isTrafficEnabled = false
						isMyLocationEnabled = false
						uiSettings.isMyLocationButtonEnabled = false
						uiSettings.setLogoBottomMargin(- 100)
						uiSettings.isZoomControlsEnabled = false

						setOnMarkerClickListener { marker ->
							marker.showInfoWindow()
							Handler(Looper.getMainLooper()).postDelayed({
								marker.hideInfoWindow()
							}, 800)
							true
						}
					}
				}
			}, update = { mapView ->
				val currentLocation = if (GlobalData.currentLocation != null) {
					LatLng(GlobalData.currentLocation?.latitude !!,
						GlobalData.currentLocation?.longitude !!)
				} else null

				val needUpdate =
					lastRoutePoints.value != uiState.value.routePoints || lastMarkers.value != uiState.value.markers || lastCurrentLocation.value != currentLocation

				if (needUpdate) {
					mapView.map.clear()

					// 绘制路线
					uiState.value.routePoints?.let { points ->
						mapView.map.addPolyline(PolylineOptions().addAll(points).width(15f)
							.setCustomTexture(BitmapDescriptorFactory.fromResource(R.drawable.icon_road_green_arrow))
							.zIndex(1f))
					}

					// 添加标记点
					val allPoints = mutableListOf<LatLng>()

					// 添加当前位置标记
					currentLocation?.let {
						mapView.map.addMarker(MarkerOptions().position(it).title("当前位置")
							.icon(ImageUtil.vectorToBitmap(context, R.drawable.ic_current_location))
							.anchor(0.5f, 0.5f).visible(true))
						allPoints.add(it)
					}

					// 添加其他标记点
					uiState.value.markers?.let { markers ->
						mapView.map.addMarkers(markers, true)
						markers.forEach { marker ->
							allPoints.add(marker.position)
						}
					}

					// 添加路线点
					uiState.value.routePoints?.let { points ->
						allPoints.addAll(points)
					}

					// 计算边界
					if (allPoints.isNotEmpty()) {
						try {
							val boundsBuilder = LatLngBounds.builder()
							allPoints.forEach { point ->
								boundsBuilder.include(point)
							}

							mapView.map.animateCamera(CameraUpdateFactory.newLatLngBounds(
								boundsBuilder.build(),
								100))
						} catch (e : Exception) { // 如果边界计算失败，使用救援点作为中心
							jpushBean?.let { bean ->
								if (bean.lat != null && bean.lat != 0.0 && bean.lng != null && bean.lng != 0.0) {
									mapView.map.animateCamera(CameraUpdateFactory.newLatLngZoom(
										LatLng(bean.lat, bean.lng),
										15f))
								}
							}
						}
					}

					// 更新状态
					lastRoutePoints.value = uiState.value.routePoints
					lastMarkers.value = uiState.value.markers
					lastCurrentLocation.value = currentLocation
				}
			})
		}
	}
}

@Composable
private fun OrderItemView(jpushBean : JpushBean?, remainingTime : Int = 50) {
	val context = LocalContext.current
	Column(modifier = Modifier
		.fillMaxWidth()
		.background(color = Color.White)
		.padding(bottom = 16.dp)) { // 订单类型和倒计时
		Row(modifier = Modifier
			.fillMaxWidth()
			.background(brush = Brush.verticalGradient(colors = arrayListOf(Color(0xFFFFEDE3),
				Color.White)))
			.padding(horizontal = 16.dp, vertical = 12.dp),
			horizontalArrangement = Arrangement.SpaceBetween,
			verticalAlignment = Alignment.CenterVertically) {
			Text(text = jpushBean?.serviceTypeName ?: "",
				fontSize = 18.sp,
				fontWeight = FontWeight.Bold,
				color = Color.Black)
			Text(text = "${remainingTime}s",
				fontSize = 15.sp,
				color = Color(0xFFFF4200),
				fontWeight = FontWeight.Medium)
		}

		HorizontalDivider(modifier = Modifier
			.padding(horizontal = 16.dp)
			.alpha(0.08f))

		// 订单标签
		Row(modifier = Modifier
			.fillMaxWidth()
			.padding(horizontal = 16.dp, vertical = 12.dp),
			horizontalArrangement = Arrangement.SpaceBetween,
			verticalAlignment = Alignment.CenterVertically) {
			Row(verticalAlignment = Alignment.CenterVertically) {
				Box(modifier = Modifier
					.background(Color(0xFF9BA1B2), RoundedCornerShape(4.dp))
					.padding(horizontal = 6.dp, vertical = 2.dp)) {
					Text(text = "月结", color = Color.White, fontSize = 12.sp)
				}
				Spacer(modifier = Modifier.width(8.dp))
				Text(text = jpushBean?.contract ?: "", color = Color.Black, fontSize = 12.sp)
			}
			Text(text = jpushBean?.addressProperty ?: "",
				fontSize = 12.sp,
				fontWeight = FontWeight.Medium,
				color = Color(0xFFFD8205))
		}

		// 订单号
		Row(modifier = Modifier
			.fillMaxWidth()
			.padding(horizontal = 16.dp)
			.clickable { jpushBean?.taskCode?.copy(context) },
			verticalAlignment = Alignment.CenterVertically) {
			Text(text = "单号", color = Color(0xFF999999), fontSize = 13.sp)
			Spacer(modifier = Modifier.width(8.dp))
			Text(text = jpushBean?.taskCode ?: "",
				color = Color(0xFF666666),
				fontSize = 14.sp,
				fontWeight = FontWeight.Medium)
			Spacer(modifier = Modifier.width(8.dp))
			AsyncImage(model = R.drawable.sv_copy,
				contentDescription = "copy",
				modifier = Modifier.size(16.dp))
		}

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

		// 救援地址
		Row(modifier = Modifier
			.fillMaxWidth()
			.padding(horizontal = 16.dp),
			verticalAlignment = Alignment.Top) {
			AsyncImage(model = R.drawable.sv_rescuing,
				contentDescription = "rescue",
				modifier = Modifier.size(16.dp))
			Spacer(modifier = Modifier.width(8.dp))
			Text(text = jpushBean?.address ?: "",
				color = Color.Black,
				fontSize = 15.sp,
				fontWeight = FontWeight.Medium)
		}

		// 目的地地址
		if (! jpushBean?.distAddress.isNullOrBlank()) {
			Spacer(modifier = Modifier.height(16.dp))
			HorizontalDivider(modifier = Modifier
				.padding(horizontal = 24.dp)
				.alpha(0.1f))
			Spacer(modifier = Modifier.height(16.dp))
			Row(modifier = Modifier
				.fillMaxWidth()
				.padding(horizontal = 16.dp),
				verticalAlignment = Alignment.Top) {
				AsyncImage(model = R.drawable.sv_dist,
					contentDescription = "destination",
					modifier = Modifier.size(16.dp))
				Spacer(modifier = Modifier.width(8.dp))
				Text(text = jpushBean?.distAddress ?: "",
					color = Color.Black,
					fontSize = 15.sp,
					fontWeight = FontWeight.Medium)
			}
		}

		Spacer(modifier = Modifier.height(16.dp))
	}
}