package com.example.initiateaphonecallapp.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import androidx.lifecycle.MutableLiveData
import com.example.initiateaphonecallapp.data.model.WebSocketMessage
import com.example.initiateaphonecallapp.enums.MessageType
import com.google.gson.Gson
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.*
import okio.ByteString
import java.util.concurrent.TimeUnit

class WebSocketService : Service() {

    private var webSocket: WebSocket? = null
    private var currentToken: String? = null
    private val client = OkHttpClient.Builder()
        .readTimeout(3, TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)
        .build()

    // LiveData 用于观察 WebSocket 状态和消息
    companion object {
        val webSocketStatus = MutableLiveData<WebSocketStatus>()
        val receivedMessages = MutableLiveData<WebSocketMessage>()
    }

    enum class WebSocketStatus {
        CONNECTING, CONNECTED, DISCONNECTED, ERROR
    }

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onCreate() {
        super.onCreate()
        // 不在 onCreate 中连接，等待 token
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        intent?.let {
            when (it.action) {
                "CONNECT" -> {
                    val token = it.getStringExtra("TOKEN")
                    token?.let { authToken ->
                        currentToken = authToken
                        connectWebSocket(authToken)
                    } ?: run {
                        println("❌ WebSocketService: 未提供 token，无法连接")
                    }
                }
                "DISCONNECT" -> {
                    disconnectWebSocket()
                }
                "RECONNECT" -> {
                    val token = it.getStringExtra("TOKEN") ?: currentToken
                    token?.let { authToken ->
                        disconnectWebSocket()
                        connectWebSocket(authToken)
                    }
                }

                else -> {}
            }
        }
        return START_STICKY
    }

    private fun connectWebSocket(token: String) {
        // 构建带 token 的 WebSocket URL
        val url = "ws://120.26.58.34/prod-api/ws/call?token=$token"
//        val url = "ws://121.43.240.248/prod-api/ws/call?token=$token"

        println("🔗 WebSocketService: 正在连接 WebSocket: $url")

        val request = Request.Builder()
            .url(url)
            .build()

        webSocketStatus.postValue(WebSocketStatus.CONNECTING)

        webSocket = client.newWebSocket(request, object : WebSocketListener() {
            override fun onOpen(webSocket: WebSocket, response: Response) {
                webSocketStatus.postValue(WebSocketStatus.CONNECTED)
                println("✅ WebSocketService: 连接成功")

                // 可以在这里发送额外的认证消息（如果需要）
                // val authMessage = """{"type":"auth","token":"$token"}"""
                // webSocket.send(authMessage)
            }

            override fun onMessage(webSocket: WebSocket, text: String) {
                println("📨 WebSocketService: 收到消息: $text")
                handleMessage(text)
            }

            override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
                handleMessage(bytes.utf8())
            }

            override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
                webSocketStatus.postValue(WebSocketStatus.DISCONNECTED)
                println("🔌 WebSocketService: 连接正在关闭: $reason")
            }

            override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
                webSocketStatus.postValue(WebSocketStatus.DISCONNECTED)
                println("🔌 WebSocketService: 连接已关闭: $reason")
            }

            override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
                webSocketStatus.postValue(WebSocketStatus.ERROR)
                println("❌ WebSocketService: 连接失败: ${t.message}")

                // 重连逻辑
                CoroutineScope(Dispatchers.IO).launch {
                    Thread.sleep(5000)
                    currentToken?.let { token ->
                        println("🔄 WebSocketService: 尝试重新连接...")
                        connectWebSocket(token)
                    }
                }
            }
        })
    }

    private fun handleMessage(message: String) {
        try {
            println("🔍 WebSocketService: 解析消息: $message")

            val webSocketMessage = Gson().fromJson(message, WebSocketMessage::class.java)
            receivedMessages.postValue(webSocketMessage)

            // 处理电话号码消息
            if (webSocketMessage.action == MessageType.CALL && webSocketMessage.phone != null) {
                println("📞 WebSocketService: 接收到电话呼叫请求，号码: ${webSocketMessage.phone}")
                handlePhoneCallMessage(webSocketMessage.phone!!)
            } else {
                println("ℹ️ WebSocketService: 收到其他类型消息: ${webSocketMessage.action}")
            }
        } catch (e: Exception) {
            println("❌ WebSocketService: 消息解析错误: ${e.message}")
            e.printStackTrace()
        }
    }

    private fun handlePhoneCallMessage(phoneNumber: String) {
        println("📱 WebSocketService: 准备启动电话服务，号码: $phoneNumber")

        try {
            // 调用 PhoneCallService 发起电话
            val intent = Intent(this, PhoneCallService::class.java).apply {
                action = "ACTION_INITIATE_CALL"
                putExtra("PHONE_NUMBER", phoneNumber)
            }

            println("📱 WebSocketService: 创建 Intent: $intent")
            println("📱 WebSocketService: Intent action: ${intent.action}")
            println("📱 WebSocketService: Intent extras: ${intent.extras}")

            startService(intent)
            println("✅ WebSocketService: 电话服务启动请求已发送")

        } catch (e: Exception) {
            println("❌ WebSocketService: 启动电话服务失败: ${e.message}")
            e.printStackTrace()
        }
    }

    private fun disconnectWebSocket() {
        webSocket?.close(1000, "Manual disconnect")
//        client.dispatcher.executorService.shutdown()
        webSocketStatus.postValue(WebSocketStatus.DISCONNECTED)
        println("🔌 WebSocketService: 手动断开连接")
    }

    // 发送消息到 WebSocket 服务器
    fun sendMessage(message: String): Boolean {
        return try {
            webSocket?.send(message)
            println("📤 WebSocketService: 发送消息: $message")
            true
        } catch (e: Exception) {
            println("❌ WebSocketService: 发送消息失败: ${e.message}")
            false
        }
    }

    override fun onDestroy() {
        disconnectWebSocket()
        super.onDestroy()
    }
}