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.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.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.BottomSheetScaffold
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.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
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.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) }

	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()
					}

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

		lifecycleOwner.lifecycle.addObserver(observer)
		onDispose {
			try {
				lifecycleOwner.lifecycle.removeObserver(observer)
			} 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) {
		vm.updateState(uiState.value.copy(refuseSuccess = false))
		context.finish()
	}

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

	if (uiState.value.acceptOrderDialog == true) {
		CommonDialog(title = "请确认是否接受该任务！",
			confirmText = "确认接单",
			cancelText = "再想想",
			cancelEnable = true,
			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?.contract,
			uiState.value.jpushBean?.hasReplaceBatteryCapable == 2,
			dismiss = {
				vm.updateState(uiState.value.copy(showTaskNotesDialog = false))
			},
			confirm = {
				vm.updateState(uiState.value.copy(showTaskNotesDialog = false))
				vm.dispatch(NewOrderVm.Action.AcceptOrder)
			})
	}

	var sheetExpandHeight = remember { mutableStateOf(0.dp) }
	val localDensity = LocalDensity.current

	BottomSheetScaffold(scaffoldState = scaffoldState,
		topBar = { HeadViewNotBack(title = "新订单") },
		sheetContent = {
			val uiBean = NewOrderItemUIBean(taskCode = uiState.value.jpushBean?.taskCode,
				addressProperty = uiState.value.jpushBean?.addressProperty,
				address = uiState.value.jpushBean?.address,
				distAddress = uiState.value.jpushBean?.distAddress,
				serviceTypeName = uiState.value.jpushBean?.serviceTypeName,
				orderSource = uiState.value.jpushBean?.contract,
				settleType = uiState.value.jpushBean?.settleType,
				bottomTextString = "接单",
				reserveTime = (uiState.value.jpushBean?.appointTime
					?: "").takeIf { uiState.value.jpushBean?.isAppoint == 1 } ?: "",
				uiType = NewOrderUiType.ACCEPT)

			Box(modifier = Modifier
				.fillMaxWidth()
				.onSizeChanged { coordinates ->
					sheetExpandHeight.value = with(localDensity) { coordinates.height.toDp() }
				}) {
				NewOrderItem(uiBean, goAccept = {
					vm.dispatch(NewOrderVm.Action.ShowTaskNotes)
				}, refuelOrder = {
					vm.updateState(uiState.value.copy(refuelOrderDialog = true))
				})
			}
		},
		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
			.wrapContentSize()
			.padding(top = paddingValues.calculateTopPadding(),
				bottom = if (bottomSheetState.currentValue == SheetValue.PartiallyExpanded) {
					0.dp
				} else {
					sheetExpandHeight.value
				})) {
			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 ->
				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))
				}

				mapView.map.addMarkers(uiState.value.markers, false)

				// 添加当前位置标记
				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))
				}

				// 计算地图显示范围
				val bounds = LatLngBounds.Builder().apply {
					uiState.value.routePoints?.forEach {
						include(LatLng(it.latitude, it.longitude))
					}
				}.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))
					}
				}

			})
		}
	}
}

@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))
	}
}