package com.example.initiateaphonecallapp.ui.home

import android.app.Application
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.initiateaphonecallapp.data.model.CallRecord
import com.example.initiateaphonecallapp.data.model.SelectedAudioFile
import com.example.initiateaphonecallapp.enums.CallStatus
import com.example.initiateaphonecallapp.enums.MessageType
import com.example.initiateaphonecallapp.manager.CallRecordManager
import com.example.initiateaphonecallapp.service.PhoneCallService
import com.example.initiateaphonecallapp.service.WebSocketService
import com.example.initiateaphonecallapp.utils.CallRecordScanner
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class HomeViewModel(application: Application) : AndroidViewModel(application) {

//    // 使用 CallRecordManager 的状态
//    val callRecords: StateFlow<List<com.example.initiateaphonecallapp.data.model.CallRecord>> = CallRecordManager.callRecords
//    val currentCall: StateFlow<com.example.initiateaphonecallapp.data.model.CallRecord?> = CallRecordManager.currentCall
//    val recentCall: StateFlow<com.example.initiateaphonecallapp.data.model.CallRecord?> = CallRecordManager.recentCall
//    val uploadStatus: StateFlow<CallRecordManager.UploadStatus> = CallRecordManager.uploadStatus
//
//
//
//    private val _webSocketStatus = MutableStateFlow(WebSocketService.WebSocketStatus.DISCONNECTED)
//    val webSocketStatus: StateFlow<WebSocketService.WebSocketStatus> = _webSocketStatus.asStateFlow()
//
//    private val _receivedMessages = MutableStateFlow<List<com.example.initiateaphonecallapp.data.model.WebSocketMessage>>(emptyList())
//    val receivedMessages: StateFlow<List<com.example.initiateaphonecallapp.data.model.WebSocketMessage>> = _receivedMessages.asStateFlow()

    // 使用 CallRecordManager 的状态流
    private val _callRecords = MutableStateFlow(CallRecordManager.callRecords.value)
    val callRecords: StateFlow<List<CallRecord>> = _callRecords.asStateFlow()

    private val _currentCall = MutableStateFlow(CallRecordManager.currentCall.value)
    val currentCall: StateFlow<CallRecord?> = _currentCall.asStateFlow()

    private val _recentCall = MutableStateFlow(CallRecordManager.recentCall.value)
    val recentCall: StateFlow<CallRecord?> = _recentCall.asStateFlow()

    private val _uploadStatus = MutableStateFlow(CallRecordManager.uploadStatus.value)
    val uploadStatus: StateFlow<CallRecordManager.UploadStatus> = _uploadStatus.asStateFlow()

    private val _selectedAudioFile = MutableStateFlow(CallRecordManager.selectedAudioFile.value)
    val selectedAudioFile: StateFlow<SelectedAudioFile?> = _selectedAudioFile.asStateFlow()

    private val _webSocketStatus = MutableStateFlow(WebSocketService.WebSocketStatus.DISCONNECTED)
    val webSocketStatus: StateFlow<WebSocketService.WebSocketStatus> = _webSocketStatus.asStateFlow()

    private val _receivedMessages = MutableStateFlow<List<com.example.initiateaphonecallapp.data.model.WebSocketMessage>>(emptyList())
    val receivedMessages: StateFlow<List<com.example.initiateaphonecallapp.data.model.WebSocketMessage>> = _receivedMessages.asStateFlow()


//    // 选择的音频文件通过 CallRecordManager 管理
//    val selectedAudioFile: StateFlow<SelectedAudioFile?>
//        get() = CallRecordManager.selectedAudioFile

    // 通话状态监听
    private var callStartTime: Date? = null



    fun setSelectedAudioFile(uri: Uri, fileName: String) {
        if (uri == Uri.EMPTY) {
            CallRecordManager.setSelectedAudioFile(null)
        } else {
            CallRecordManager.setSelectedAudioFile(SelectedAudioFile(uri, fileName))
        }
    }


    // 获取当前选择的音频文件信息
    fun getSelectedAudioFile(): SelectedAudioFile? {
        return CallRecordManager.getSelectedAudioFile()
    }

    fun reconnectWebSocket(token: String) {
        viewModelScope.launch {
            val intent = Intent(getApplication(), WebSocketService::class.java).apply {
                action = "RECONNECT"
                putExtra("TOKEN", token)
            }
            getApplication<Application>().startService(intent)
            println("🔄 HomeViewModel: 请求重连 WebSocket")
        }
    }
    // 清除选择的文件
    fun clearSelectedAudioFile() {
        CallRecordManager.setSelectedAudioFile(null)
    }

    // 手动上传最近通话记录
    fun manuallyUploadRecentCall() {
        CallRecordManager.manuallyUploadRecentCall()
    }

    // 清除最近通话记录
    fun clearRecentCall() {
        CallRecordManager.clearRecentCall()
    }

    // 添加自动扫描状态（用于调试）
    private val _autoScanStatus = MutableStateFlow("")
    val autoScanStatus: StateFlow<String> = _autoScanStatus.asStateFlow()



    private fun observeCallRecordManager() {
        viewModelScope.launch {
            CallRecordManager.callRecords.collect { records ->
                _callRecords.value = records
                println("🏠 HomeViewModel: 通话记录更新，数量: ${records.size}")
            }
        }

        viewModelScope.launch {
            CallRecordManager.currentCall.collect { call ->
                _currentCall.value = call
                println("🏠 HomeViewModel: 当前通话更新: ${call?.phoneNumber ?: "无"}")
            }
        }

        viewModelScope.launch {
            CallRecordManager.recentCall.collect { recent ->
                _recentCall.value = recent
                println("🏠 HomeViewModel: 最近通话更新: ${recent?.phoneNumber ?: "无"}")
            }
        }

        viewModelScope.launch {
            CallRecordManager.uploadStatus.collect { status ->
                _uploadStatus.value = status
                println("🏠 HomeViewModel: 上传状态更新: $status")
            }
        }

        viewModelScope.launch {
            CallRecordManager.selectedAudioFile.collect { audioFile ->
                _selectedAudioFile.value = audioFile
                println("🏠 HomeViewModel: 音频文件更新: ${audioFile?.fileName ?: "无"}")
            }
        }
    }

    private fun observeWebSocketStatus() {
        viewModelScope.launch {
            WebSocketService.webSocketStatus.observeForever { status ->
                viewModelScope.launch {
                    _webSocketStatus.value = status
                    println("🏠 HomeViewModel: WebSocket 状态更新为: $status")
                }
            }
        }
    }

    private fun observeWebSocketMessages() {
        WebSocketService.receivedMessages.observeForever { message ->
            message?.let {
                viewModelScope.launch {
                    _receivedMessages.value = _receivedMessages.value + it
                    println("🏠 HomeViewModel: 收到新消息: $it")

                    // 如果是电话呼叫消息，开始通话记录
                    if (it.action == MessageType.CALL && it.phone != null) {
                        CallRecordManager.startCallRecord(it.phone!!)
                        // WebSocketService 会自动处理电话呼叫
                    }
                }
            }
        }
    }
    init {

        // 观察 CallRecordManager 的所有状态变化
        observeCallRecordManager()

        // 观察 WebSocket 状态
        observeWebSocketStatus()

        // 监听 WebSocket 消息
        observeWebSocketMessages()
        // 观察 WebSocket 状态
        viewModelScope.launch {
            // 监听 WebSocket 状态变化
            WebSocketService.webSocketStatus.observeForever { status ->
                viewModelScope.launch {
                    _webSocketStatus.value = status
                    println("🏠 HomeViewModel: WebSocket 状态更新为: $status")
                }
            }
        }

        // 监听 WebSocket 消息
        WebSocketService.receivedMessages.observeForever { message ->
            message?.let {
                viewModelScope.launch {
                    _receivedMessages.value = _receivedMessages.value + it
                    println("🏠 HomeViewModel: 收到新消息: $it")

                    /// 如果是电话呼叫消息，开始通话记录
                    if (it.action == MessageType.CALL && it.phone != null) {
                        CallRecordManager.startCallRecord(it.phone!!)
                        // WebSocketService 会自动处理电话呼叫
                    }
                }
            }
        }
    }
    //==========================================================================================================================================================================================

// 在 HomeViewModel 中添加以下代码

    private val _callRecordFiles = MutableStateFlow<List<CallRecordScanner.CallRecordFile>>(emptyList())
    val callRecordFiles: StateFlow<List<CallRecordScanner.CallRecordFile>> = _callRecordFiles.asStateFlow()

    private val _scanStatus = MutableStateFlow("")
    val scanStatus: StateFlow<String> = _scanStatus.asStateFlow()

    // 扫描通话录音文件
    // 扫描通话录音文件
    fun scanCallRecords() {
        viewModelScope.launch {
            try {
                _scanStatus.value = "正在扫描通话录音..."
                println("🔍 开始扫描所有通话录音文件")


                // 使用新的扫描方法（不限制文件名格式）
                val records = CallRecordScanner.scanAllCallRecords(getApplication())
                _callRecordFiles.value = records

                val status = when {
                    records.isNotEmpty() -> "找到 ${records.size} 个录音文件（宽松匹配）"
                    CallRecordScanner.hasAccessibleRecordDirs() -> "找到录音目录，但没有录音文件"
                    else -> "未找到通话录音目录"
                }
                _scanStatus.value = status

                println("📊 扫描完成: $status")

                // 打印查询路径信息
                println("📁 查询路径:")
                CallRecordScanner.getQueryPaths().forEach { (brand, path) ->
                    println("   $brand: $path")
                }

                // 打印找到的文件信息
                records.forEach { record ->
                    println("📄 文件: ${record.displayName}")
                    println("   📞 解析手机号: ${record.phoneNumber ?: "未解析"}")
                    println("   🏷️ 品牌: ${record.brand}")
                    println("   📁 目录: ${record.directory}")
                }

            } catch (e: Exception) {
                _scanStatus.value = "扫描失败: ${e.message}"
                println("❌ 扫描失败: ${e.message}")
            }
        }
    }

    // 选择录音文件
    fun selectCallRecordFile(recordFile: CallRecordScanner.CallRecordFile) {
        viewModelScope.launch {
            try {
                setSelectedAudioFile(recordFile.uri, recordFile.displayName)
                _scanStatus.value = "已选择: ${recordFile.displayName}"
                println("✅ 选择录音文件: ${recordFile.displayName}")
            } catch (e: Exception) {
                _scanStatus.value = "选择失败: ${e.message}"
                println("❌ 选择录音文件失败: ${e.message}")
            }
        }
    }



}