package com.za.ui.servicing.go_accident

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
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.SheetValue
import androidx.compose.material3.rememberBottomSheetScaffoldState
import androidx.compose.material3.rememberStandardBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
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.unit.dp
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 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.common.GlobalData
import com.za.common.util.ImageUtil
import com.za.ext.finish
import com.za.ext.goNextPage
import com.za.servicing.R
import com.za.ui.new_order.NewOrderItem
import com.za.ui.new_order.NewOrderItemUIBean
import com.za.ui.new_order.NewOrderUiType
import com.za.ui.servicing.view.InServicingHeadView
import com.za.ui.servicing.view.ServiceOperation

class GoAccidentSiteActivity : BaseActivity() {
	@Composable
	override fun ContentView() {
		GoAccidentSiteScreen()
	}
}

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

	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(GoAccidentSiteVm.Action.Init)
				}

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

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

	if (uiState.value.showOfflineDialog == true) {
		CommonDialog(cancelText = "取消",
			confirmText = "离线上传",
			title = "任务提交失败，是否离线提交？",
			cancelEnable = true,
			cancel = {
				vm.dispatch(GoAccidentSiteVm.Action.UpdateState(uiState.value.copy(
					showOfflineDialog = false)))
			},
			dismiss = {
				vm.dispatch(GoAccidentSiteVm.Action.UpdateState(uiState.value.copy(
					showOfflineDialog = false)))
			},
			confirm = {
				vm.dispatch(GoAccidentSiteVm.Action.UpdateState(uiState.value.copy(
					showOfflineDialog = false)))
				vm.dispatch(GoAccidentSiteVm.Action.UpdateOffline)
			})
	}

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


	BottomSheetScaffold(scaffoldState = scaffoldState,
		topBar = {
			InServicingHeadView(title = "救援车发车，正在赶往现场",
				onBack = { context.finish() },
				orderInfo = uiState.value.orderInfo)
		},
		sheetContent = {
			val uiBean = NewOrderItemUIBean(taskCode = uiState.value.orderInfo?.taskCode,
				addressProperty = uiState.value.orderInfo?.addressProperty,
				address = uiState.value.orderInfo?.address,
				distAddress = uiState.value.orderInfo?.distAddress,
				serviceTypeName = uiState.value.orderInfo?.serviceTypeName,
				orderSource = uiState.value.orderInfo?.orderSource,
				settleType = uiState.value.orderInfo?.settleType,
				bottomTextString = "到达事发地",
				expectArriveTime = uiState.value.orderInfo?.expectArriveTime,
				uiType = NewOrderUiType.SERVICING)

			Box(modifier = Modifier
				.fillMaxWidth()
				.onSizeChanged { coordinates ->
					sheetExpandHeight.value = with(localDensity) { coordinates.height.toDp() }
				}) {
				NewOrderItem(uiBean, goNextPage = {
					vm.dispatch(GoAccidentSiteVm.Action.UpdateState(uiState.value.copy(
						isGoNextPageDialog = true)))
				})
			}
		},
		sheetPeekHeight = 180.dp,
		sheetShape = RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp),
		sheetContainerColor = Color.White,
		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
						}
					}
				}
				mapView
			}, 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))
				}

				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(100f)))
				} catch (e : Exception) {
					GlobalData.currentLocation?.let {
						mapView.map.animateCamera(CameraUpdateFactory.newLatLngZoom(LatLng(it.latitude,
							it.longitude), 15f))
					}
				}
			})

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