package com.za.ui.servicing.wait_to_start

import android.os.Bundle
import android.os.Handler
import android.os.Looper
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.remember
import androidx.compose.ui.AbsoluteAlignment
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
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.blankj.utilcode.util.ConvertUtils
import com.za.base.BaseActivity
import com.za.base.theme.headBgColor
import com.za.base.view.CommonDialog
import com.za.common.GlobalData
import com.za.common.util.ImageUtil
import com.za.common.util.ServicingSpeechManager
import com.za.ext.copy
import com.za.ext.finish
import com.za.ext.goNextPage
import com.za.ext.navigationActivity
import com.za.servicing.R
import com.za.ui.servicing.inservice_people_confirm.ServicePeopleConfirmActivity
import com.za.ui.servicing.view.InServicingHeadView
import com.za.ui.servicing.view.ServiceOperation


class WaitToStartActivity : BaseActivity() {
	@Composable
	override fun ContentView() {
		WaitToStartScreen()
	}
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WaitToStartScreen(vm : WaitToStartVm = viewModel()) {
	val uiState = vm.uiState.collectAsStateWithLifecycle()
	val context = LocalContext.current
	val lifecycleOwner = LocalLifecycleOwner.current
	val mapView = remember { MapView(context) }

	// 添加 BottomSheet 状态
	val bottomSheetState = rememberStandardBottomSheetState(initialValue = SheetValue.Expanded)
	val scaffoldState = rememberBottomSheetScaffoldState(bottomSheetState = bottomSheetState)

	DisposableEffect(key1 = lifecycleOwner) {
		val observer = LifecycleEventObserver { _, event ->
			when (event) {
				Lifecycle.Event.ON_CREATE -> {
					mapView.onCreate(Bundle())
					vm.dispatch(WaitToStartVm.Action.Init)
					ServicingSpeechManager.playStartTip(context)
				}

				Lifecycle.Event.ON_RESUME -> mapView.onResume()
				Lifecycle.Event.ON_PAUSE -> mapView.onPause()
				Lifecycle.Event.ON_DESTROY -> mapView.onDestroy()
				else -> {}
			}
		}

		lifecycleOwner.lifecycle.addObserver(observer)
		onDispose {
			lifecycleOwner.lifecycle.removeObserver(observer)
		}
	}

	if (uiState.value.goNextPage != null) {
		goNextPage(uiState.value.goNextPage?.nextState, context)
		vm.dispatch(WaitToStartVm.Action.UpdateState(uiState.value.copy(goNextPage = null)))
	}

	if (uiState.value.isGoNextPageDialog == true) {
		CommonDialog(cancelText = "取消",
			confirmText = "前往下一步",
			title = "是否前往下一步？",
			cancelEnable = true,
			cancel = {
				vm.dispatch(WaitToStartVm.Action.UpdateState(uiState.value.copy(isGoNextPageDialog = false)))
			},
			dismiss = {
				vm.dispatch(WaitToStartVm.Action.UpdateState(uiState.value.copy(isGoNextPageDialog = false)))
			},
			confirm = {
				vm.dispatch(WaitToStartVm.Action.UpdateState(uiState.value.copy(isGoNextPageDialog = false)))
				vm.dispatch(WaitToStartVm.Action.UpdateTask)
			})
	}

	if (uiState.value.showServicePeopleConfirmDialog == true) {
		CommonDialog(cancelText = "取消",
			confirmText = "去核验",
			title = "服务技师信息核验",
			cancelEnable = true,
			cancel = {
				vm.dispatch(WaitToStartVm.Action.UpdateState(uiState.value.copy(
					showServicePeopleConfirmDialog = false)))
			},
			dismiss = {
				vm.dispatch(WaitToStartVm.Action.UpdateState(uiState.value.copy(
					showServicePeopleConfirmDialog = false)))
			},
			confirm = {
				vm.dispatch(WaitToStartVm.Action.UpdateState(uiState.value.copy(
					showServicePeopleConfirmDialog = false)))
				context.navigationActivity(ServicePeopleConfirmActivity::class.java, true)
			})
	}

	BottomSheetScaffold(scaffoldState = scaffoldState,
		topBar = {
			InServicingHeadView(title = "调度成功，等待发车",
				onBack = { context.finish() },
				orderInfo = uiState.value.orderInfo)
		},
		sheetContent = {
			Column(modifier = Modifier
				.fillMaxWidth()
				.wrapContentHeight()
				.verticalScroll(rememberScrollState())) { // 滑动指示器
				Box(modifier = Modifier
					.fillMaxWidth()
					.padding(vertical = 8.dp),
					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 = 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.orderInfo?.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.orderInfo?.settleType == 1 }
								?: "现金", color = Color.White, fontSize = 12.sp)
						}

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

						Text(text = uiState.value.orderInfo?.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.orderInfo?.taskCode?.copy(context)
						}) {
						Text(text = "单号", color = Color(0xFF999999), fontSize = 13.sp)

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

						Text(text = uiState.value.orderInfo?.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.orderInfo?.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.orderInfo?.address ?: "",
								color = Color.Black,
								fontSize = 15.sp,
								fontWeight = FontWeight.Medium)
						}

						// 目的地
						if (! uiState.value.orderInfo?.distAddress.isNullOrBlank()) {
							Row(verticalAlignment = Alignment.Top,
								modifier = Modifier.clickable { // 点击目的地时移动地图到目的地位置
									uiState.value.orderInfo?.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.orderInfo?.distAddress ?: "",
									color = Color.Black,
									fontSize = 15.sp,
									fontWeight = FontWeight.Medium)
							}
						}
					}

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

					// 发车按钮
					Button(onClick = {
						if (! GlobalData.isMaster && GlobalData.driverInfoBean != null && GlobalData.driverInfoBean?.authStatus == 1) {
							vm.dispatch(WaitToStartVm.Action.UpdateState(uiState.value.copy(
								showServicePeopleConfirmDialog = true)))
							return@Button
						}
						vm.dispatch(WaitToStartVm.Action.UpdateState(uiState.value.copy(
							isGoNextPageDialog = true)))
					},
						modifier = Modifier
							.fillMaxWidth()
							.height(44.dp)
							.padding(horizontal = 16.dp),
						colors = ButtonDefaults.buttonColors(containerColor = headBgColor),
						shape = RoundedCornerShape(8.dp)) {
						Text(text = "发车",
							color = Color.White,
							fontSize = 16.sp,
							fontWeight = FontWeight.Medium)
					}

					Spacer(modifier = Modifier.height(16.dp))
				}
			}
		},
		sheetPeekHeight = 180.dp,
		sheetShape = RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp),
		sheetContainerColor = Color.White,
		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() // 800ms后隐藏信息窗口
							Handler(Looper.getMainLooper()).postDelayed({
								marker.hideInfoWindow()
							}, 800)
							true
						}
					}
				}
			}, update = { // 清除旧标记和路线
				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))
				}

				// 再添加标记点，确保标记点在路线上层
				// 添加当前位置标记
				if (GlobalData.currentLocation != null) {
					mapView.map.addMarker(MarkerOptions().position(LatLng(GlobalData.currentLocation?.latitude !!,
						GlobalData.currentLocation?.longitude !!)).title("当前位置")
						.icon(ImageUtil.vectorToBitmap(context, R.drawable.ic_current_location))
						.anchor(0.5f, 0.5f).visible(true))
				}

				// 添加救援地标记
				uiState.value.orderInfo?.let { order ->
					if (order.lat != null && order.lat != 0.0 && order.lng != null && order.lng != 0.0 && GlobalData.currentLocation != null) {
						mapView.map.addMarker(MarkerOptions().position(LatLng(order.lat !!,
							order.lng !!)).title("救援地点")
							.icon(BitmapDescriptorFactory.fromResource(R.mipmap.sv_rescuing_map))
							.anchor(0.5f, 0.5f))
					}

					// 添加目的地标记
					if (order.distLat != null && order.distLat != 0.0 && order.distLng != null && order.distLng != 0.0 && GlobalData.currentLocation != null) {
						mapView.map.addMarker(MarkerOptions().position(LatLng(order.distLat !!,
							order.distLng !!)).title("目的地")
							.icon(ImageUtil.vectorToBitmap(context, R.drawable.sv_map_dist))
							.anchor(0.5f, 0.5f))
					}
				}

				// 最后调整地图显示范围
				// 计算地图显示范围
				val bounds = LatLngBounds.Builder().apply { // 添加当前位置
					GlobalData.currentLocation?.let {
						include(LatLng(it.latitude, it.longitude))
					}

					// 添加救援地点
					uiState.value.orderInfo?.let { order ->
						if (order.lat != null && order.lat != 0.0 && order.lng != null && order.lng != 0.0) {
							include(LatLng(order.lat !!, order.lng !!))
						}

						// 添加目的地
						if (order.distLat != null && order.distLat != 0.0 && order.distLng != null && order.distLng != 0.0) {
							include(LatLng(order.distLat !!, order.distLng !!))
						}
					}
				}.build()

				// 调整地图显示范围，确保所有点都可见
				try {
					mapView.map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds,
						ConvertUtils.dp2px(50f)))
				} catch (e : Exception) { // 如果计算边界失败，则使用默认缩放级别
					GlobalData.currentLocation?.let {
						mapView.map.animateCamera(CameraUpdateFactory.newLatLngZoom(LatLng(it.latitude,
							it.longitude), 15f))
					}
				}
			})

			ServiceOperation(orderInfo = uiState.value.orderInfo)
		}
	}
}
