package com.za.base

import android.Manifest
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import android.telephony.PhoneStateListener
import android.telephony.SignalStrength
import android.telephony.TelephonyCallback
import android.telephony.TelephonyManager
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
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.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
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.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.app.ActivityCompat
import com.blankj.utilcode.util.AppUtils
import com.za.base.theme.bgColor
import com.za.base.view.HeadView
import com.za.bean.BaseResponse
import com.za.bean.UpdateVersionBean
import com.za.bean.UpdateVersionRequest
import com.za.common.GlobalData
import com.za.common.log.LogUtil
import com.za.ext.finish
import com.za.net.BaseObserver
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.Body
import retrofit2.http.POST
import java.util.concurrent.TimeUnit

data class Route(val name : String,
	val url : String,
	val id : String = name,
	val type : Int) // 添加id字段用于唯一标识

// 定义所有可用线路
val availableRoutes = if (AppConfig.isRelease) {
	listOf(
		Route("主线路", "https://api.sinoassist.com", "main", type = Const.NetEnv.Main),
		Route("备用线路",
			"http://interface.review.sino-assist.com",
			"review",
			type = Const.NetEnv.Review),
	)
} else {
	listOf(Route("CRM1", "https://api1.sino-assist.com", "crm1", type = Const.NetEnv.CRM1),
		Route("CRM2", "https://api2.sino-assist.com", "crm2", type = Const.NetEnv.CRM2),
		Route("UAT", "https://api-uat.sino-assist.com", "uat", type = Const.NetEnv.UAT))
}

// 定义检测状态枚举
enum class DetectionStatus {
	UNKNOWN, // 未检测
	CHECKING, // 检测中
	NORMAL, // 正常
	ABNORMAL // 异常
}

class NetworkRouteSelectionActivity : BaseActivity() {
	@Composable
	override fun ContentView() {
		NetworkRouteScreen(telephonyManager = getSystemService(TELEPHONY_SERVICE) as TelephonyManager,
			connectivityManager = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager)
	}
}

@Composable
fun NetworkInfo(telephonyManager : TelephonyManager, connectivityManager : ConnectivityManager) {
	val context = LocalContext.current
	var networkType by remember { mutableStateOf("") }
	var signalStrength by remember { mutableIntStateOf(- 1) }
	var operatorName by remember { mutableStateOf("") }
	val scope = rememberCoroutineScope()

	// 更新网络信息
	LaunchedEffect(Unit) {
		if (ActivityCompat.checkSelfPermission(context,
				Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
		) {            // 获取运营商名称
			operatorName = telephonyManager.networkOperatorName

			// 使用新的 API 获取网络类型
			val networkCapabilities =
				connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)

			networkType = when {
				networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true -> "WiFi"
				networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) == true -> {
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
						when (telephonyManager.dataNetworkType) {
							TelephonyManager.NETWORK_TYPE_LTE -> "4G"
							TelephonyManager.NETWORK_TYPE_NR -> "5G"
							TelephonyManager.NETWORK_TYPE_UMTS -> "3G"
							TelephonyManager.NETWORK_TYPE_EDGE -> "2G"
							else -> "未知"
						}
					} else {
						"未知"
					}
				}

				else -> "无网络"
			}

			// 使用新的 TelephonyCallback API 监听信号强度变化
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
				val callback =
					object : TelephonyCallback(), TelephonyCallback.SignalStrengthsListener {
						override fun onSignalStrengthsChanged(signalStrengths : SignalStrength) {
							scope.launch(Dispatchers.Main) {
								signalStrength = signalStrengths.level
								LogUtil.print("NetworkInfo", "signalStrength: $signalStrength")
							}
						}
					}
				telephonyManager.registerTelephonyCallback(context.mainExecutor, callback)
			} else {
				@Suppress("DEPRECATION") telephonyManager.listen(object : PhoneStateListener() {
					override fun onSignalStrengthsChanged(signalStrengths : SignalStrength) {
						super.onSignalStrengthsChanged(signalStrengths)
						scope.launch(Dispatchers.Main) {
							signalStrength = signalStrengths.level
							LogUtil.print("NetworkInfo", "signalStrength: $signalStrength")
						}
					}
				}, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS)
			}
		}
	}

	Card(modifier = Modifier
		.fillMaxWidth()
		.padding(bottom = 16.dp),
		colors = CardDefaults.cardColors(containerColor = Color.White),
		elevation = CardDefaults.elevatedCardElevation(4.dp)) {
		Column(modifier = Modifier.padding(16.dp)) {
			Text(text = "当前手机网络",
				fontSize = 20.sp,
				fontWeight = FontWeight.Bold,
				color = Color(0xFF2E7D32))

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

			Row(verticalAlignment = Alignment.CenterVertically) {
				Column {
					Text("运营商：$operatorName", fontSize = 16.sp)
					Text("网络类型：$networkType", fontSize = 16.sp)
					Text(text = "信号强度：${
						when (signalStrength) {
							0 -> "无信号"
							1 -> "弱"
							2 -> "一般"
							3 -> "良好"
							4 -> "极好"
							else -> "未知"
						}
					}", fontSize = 16.sp)
				}
			}
		}
	}
}

@Composable
fun RouteItem(
	route : Route,
	isSelected : Boolean,
	onSelect : () -> Unit,
) {
	var detectionStatus by remember { mutableStateOf(DetectionStatus.UNKNOWN) }
	var errorMessage by remember { mutableStateOf<String?>(null) }
	var isDetecting by remember { mutableStateOf(false) }
	var detectionTime by remember { mutableStateOf(0L) }

	// 检测函数
	fun detectRoute() {
		if (isDetecting) return

		isDetecting = true
		detectionStatus = DetectionStatus.CHECKING
		val startTime = System.currentTimeMillis()

		try {
			val request = UpdateVersionRequest(appVersion = AppUtils.getAppVersionName())
			NetWorkRetrofit.getDefaultService(route.url).checkConnection(request)
				.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
				.subscribe(object : BaseObserver<UpdateVersionBean>() {
					override fun doFailure(code : Int, msg : String?) {
						detectionTime = System.currentTimeMillis() - startTime
						if (code == 999) {
							detectionStatus = DetectionStatus.ABNORMAL
							errorMessage = msg
						} else {
							detectionStatus = DetectionStatus.NORMAL
						}
						isDetecting = false
					}

					override fun doSuccess(it : UpdateVersionBean?) {
						detectionTime = System.currentTimeMillis() - startTime
						detectionStatus = DetectionStatus.NORMAL
						isDetecting = false
					}
				})
		} catch (e : Exception) {
			detectionTime = System.currentTimeMillis() - startTime
			detectionStatus = DetectionStatus.ABNORMAL
			errorMessage = e.message ?: "连接失败"
			isDetecting = false
		}
	}

	// 初始检测
	LaunchedEffect(Unit) {
		detectRoute()
	}

	Column {
		Row(verticalAlignment = Alignment.CenterVertically,
			modifier = Modifier
				.fillMaxWidth()
				.clickable { onSelect() }
				.padding(vertical = 5.dp)
				.border(width = if (isSelected) 1.dp else 0.dp,
					color = if (isSelected) MaterialTheme.colorScheme.primary else Color.Transparent,
					shape = RoundedCornerShape(4.dp))
				.padding(8.dp)) {
			RadioButton(selected = isSelected, onClick = { onSelect() })

			Text(text = route.name,
				fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
				modifier = Modifier.padding(start = 8.dp))

			Spacer(Modifier.weight(1f))

			if (isDetecting) {
				CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
				Spacer(modifier = Modifier.width(8.dp))
			}

			val statusText = when (detectionStatus) {
				DetectionStatus.NORMAL -> "正常 (${detectionTime}ms)"
				DetectionStatus.ABNORMAL -> "异常 (${detectionTime}ms)"
				DetectionStatus.CHECKING -> "检测中..."
				DetectionStatus.UNKNOWN -> ""
			}

			val statusColor = when (detectionStatus) {
				DetectionStatus.NORMAL -> Color(0xFF2E7D32)
				DetectionStatus.ABNORMAL -> Color(0xFFC62828)
				DetectionStatus.CHECKING -> Color(0xFF1565C0)
				DetectionStatus.UNKNOWN -> Color.Gray
			}

			Text(text = statusText,
				color = statusColor,
				fontSize = 14.sp,
				modifier = Modifier.padding(horizontal = 8.dp))

			Box(modifier = Modifier
				.clickable(enabled = ! isDetecting) { detectRoute() }
				.background(color = MaterialTheme.colorScheme.primary,
					shape = RoundedCornerShape(5.dp))
				.padding(vertical = 5.dp, horizontal = 10.dp)) {
				Text("检测", fontSize = 12.sp, color = Color.White)
			}
		}

		// 显示错误信息（如果有）
		if (detectionStatus == DetectionStatus.ABNORMAL && errorMessage != null) {
			Text(text = "错误: $errorMessage",
				color = Color(0xFFC62828),
				fontSize = 12.sp,
				modifier = Modifier.padding(start = 40.dp, bottom = 8.dp))
		}
	}
}

@Composable
fun NetworkRouteScreen(telephonyManager : TelephonyManager,
	connectivityManager : ConnectivityManager) {


	// 原有的线路选择部分
	val context = LocalContext.current
	var selectedRoute by remember { mutableStateOf(availableRoutes.find { GlobalData.networkEnv == it.type }) }
	var showApplyDialog by remember { mutableStateOf(false) }

	// 应用当前选中的线路
	fun applySelectedRoute() {
		selectedRoute?.let {
			showApplyDialog = false
			GlobalData.networkEnv = it.type
			AppConfig.changeEnv(it.type)
		}
	}

	// 显示确认对话框
	if (showApplyDialog) {
		AlertDialog(onDismissRequest = { showApplyDialog = false },
			title = { Text("确认应用线路") },
			text = { Text("确定要将当前线路切换为 ${selectedRoute?.name} 吗？") },
			confirmButton = {
				Button(onClick = { applySelectedRoute() }) {
					Text("确定")
				}
			},
			dismissButton = {
				OutlinedButton(onClick = { showApplyDialog = false }) {
					Text("取消")
				}
			})
	}

	Scaffold(topBar = { HeadView(title = "线路选择", onBack = { context.finish() }) }) {
		Column(modifier = Modifier
			.fillMaxSize()
			.verticalScroll(state = rememberScrollState())
			.padding(it)
			.background(color = bgColor)
			.padding(20.dp),
			horizontalAlignment = Alignment.CenterHorizontally) {        // 标题卡片
			NetworkInfo(telephonyManager, connectivityManager)

			// 线路选择区域
			Card(modifier = Modifier
				.fillMaxWidth()
				.padding(bottom = 16.dp),
				colors = CardDefaults.cardColors(containerColor = Color.White),
				elevation = CardDefaults.elevatedCardElevation(4.dp)) {
				Column(modifier = Modifier.padding(16.dp)) {
					Text("选择线路",
						fontSize = 18.sp,
						fontWeight = FontWeight.Bold,
						modifier = Modifier.padding(bottom = 8.dp))

					Divider()

					availableRoutes.forEachIndexed { index, route ->
						RouteItem(route = route,
							isSelected = route == selectedRoute,
							onSelect = { selectedRoute = route })

						if (index < availableRoutes.size - 1) {
							Divider()
						}
					}
				}
			}

			// 应用按钮
			Button(onClick = { showApplyDialog = true },
				enabled = selectedRoute != null,
				modifier = Modifier.fillMaxWidth()) {
				Icon(Icons.Default.Check, contentDescription = null)
				Spacer(modifier = Modifier.width(4.dp))
				Text("应用选中线路")
			}
		}
	}
}

// 定义API接口
private interface RouteCheckApi {
	@POST("/driverApp/base/appVersion")
	fun checkConnection(@Body versionRequest : UpdateVersionRequest) : Observable<BaseResponse<UpdateVersionBean>>
}

// 在类的外部定义Retrofit管理器
private object NetWorkRetrofit {
	private val client =
		OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS).readTimeout(5, TimeUnit.SECONDS)
			.build()

	private val retrofitMap = mutableMapOf<String, Retrofit>()

	private fun getRetrofit(baseUrl : String) : Retrofit {
		return retrofitMap.getOrPut(baseUrl) {
			Retrofit.Builder().baseUrl(baseUrl).client(client)
				.addConverterFactory(GsonConverterFactory.create()) // Add this line
				.addCallAdapterFactory(RxJava3CallAdapterFactory.create()).build()
		}
	}

	fun getDefaultService(baseUrl : String) : RouteCheckApi {
		return getRetrofit(baseUrl).create(RouteCheckApi::class.java)
	}

	fun clearCache() {
		retrofitMap.clear()
	}
}
