package com.example.initiateaphonecallapp.ui.calllog

import android.content.Context
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.initiateaphonecallapp.data.model.AudioFile
import com.example.initiateaphonecallapp.data.model.CallRecord
import com.example.initiateaphonecallapp.data.model.CallRecordCheckRequest
import com.example.initiateaphonecallapp.data.model.CallRecordRequest
import com.example.initiateaphonecallapp.data.repository.CallLogRepository
import com.example.initiateaphonecallapp.enums.CallStatus
import com.example.initiateaphonecallapp.manager.AudioPlayManager
import com.example.initiateaphonecallapp.manager.CallRecordManager
import com.example.initiateaphonecallapp.utils.TimeRangeUtils
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import java.util.Date

class CallLogViewModel(
    private val callLogRepository: CallLogRepository = CallLogRepository()
) : ViewModel() {

    private val _callRecords = MutableStateFlow<List<CallRecord>>(emptyList())
    val callRecords: StateFlow<List<CallRecord>> = _callRecords.asStateFlow()

    private val _isLoading = MutableStateFlow(false)
    val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()

    private val _errorMessage = MutableStateFlow<String?>(null)
    val errorMessage: StateFlow<String?> = _errorMessage.asStateFlow()

    private val _selectedTimeRange = MutableStateFlow("全部")
    val selectedTimeRange: StateFlow<String> = _selectedTimeRange.asStateFlow()

    // 新增：音频播放相关状态
    private val _currentlyPlayingAudio = MutableStateFlow<String?>(null)
    val currentlyPlayingAudio: StateFlow<String?> = _currentlyPlayingAudio.asStateFlow()

    private val _playbackError = MutableStateFlow<String?>(null)
    val playbackError: StateFlow<String?> = _playbackError.asStateFlow()


    private val _audioFiles = mutableStateListOf<AudioFile>()
    val audioFiles: List<AudioFile> get() = _audioFiles

    var progress by mutableStateOf(0)
        private set

    var isScanning by mutableStateOf(false)
        private set

    /**
     * 播放音频
     */
    fun playAudio(audioUrl: String) {
        _playbackError.value = null

        // 如果正在播放同一个音频，则停止播放
        if (AudioPlayManager.isPlaying(audioUrl)) {
            stopAudio()
            return
        }

        AudioPlayManager.playAudio(
            audioUrl = audioUrl,
            onStart = {
                _currentlyPlayingAudio.value = audioUrl
            },
            onCompletion = {
                _currentlyPlayingAudio.value = null
            },
            onError = { error ->
                _playbackError.value = error
                _currentlyPlayingAudio.value = null
            }
        )
    }

    /**
     * 停止音频播放
     */
    fun stopAudio() {
        AudioPlayManager.stopAudio()
        _currentlyPlayingAudio.value = null
        _playbackError.value = null
    }

    /**
     * 暂停音频播放
     */
    fun pauseAudio() {
        AudioPlayManager.pauseAudio()
        _currentlyPlayingAudio.value = null
    }

    /**
     * 检查是否正在播放指定音频
     */
    fun isAudioPlaying(audioUrl: String): Boolean {
        return AudioPlayManager.isPlaying(audioUrl)
    }

    /**
     * 清除播放错误
     */
    fun clearPlaybackError() {
        _playbackError.value = null
    }

    override fun onCleared() {
        super.onCleared()
        // 清理资源
        AudioPlayManager.stopAudio()
    }

    /**
     * 加载通话记录
     * @param timeRange 时间范围描述，用于UI显示
     * @param request 实际的请求参数
     */
    fun loadCallRecords(timeRange: String = "全部", request: CallRecordRequest? = null) {
        _isLoading.value = true
        _errorMessage.value = null
        _selectedTimeRange.value = timeRange

        viewModelScope.launch {
            // 如果没有传入request，使用默认的（空参数获取全部）
            val actualRequest = request ?: TimeRangeUtils.createWeekRequest()
            val result = callLogRepository.getCallLogs(actualRequest)

            result
                .onSuccess { callRecords ->
                    _callRecords.value = callRecords
                }
                .onFailure { exception ->
                    _errorMessage.value = exception.message ?: "未知错误"
                }

            _isLoading.value = false
        }
    }

    // 扫描并处理音频文件
    @OptIn(ExperimentalCoroutinesApi::class)
    fun scanAndProcessAudio(context: Context) {
        viewModelScope.launch {
            isScanning = true
            _audioFiles.clear()
            progress = 0

            try {
                // 1️⃣ 扫描
                val files = suspendCancellableCoroutine { cont ->
                    CallRecordManager.scanAudioFiles(context) { scanned ->
                        cont.resume(scanned) {}
                    }
                }
                Log.d("ScanAudio", "扫描到 ${files.size} 个文件")

                // 2️⃣ 验证录音文件
                val fileNames = files.map { it.displayName }
                val request = CallRecordCheckRequest(data = fileNames)
                val checkResult = callLogRepository.checkCallLogs(request)
                val needUploadNames = checkResult.getOrNull() ?: emptyList()
                Log.d("ScanAudio", "需要上传的文件名列表: $needUploadNames")

                // 3️⃣ 过滤扫描结果，只保留需要上传且能提取手机号的文件
                val uploadFiles = files.filter { file ->
                    val needUpload = file.displayName in needUploadNames
                    val phoneNumber = extractPhoneNumber(file.displayName)
                    val hasPhone = phoneNumber != null

                    if (!needUpload) {
                        Log.d("ScanAudio", "文件 ${file.displayName} 不在上传列表，跳过")
                    } else if (!hasPhone) {
                        Log.d("ScanAudio", "文件 ${file.displayName} 没有手机号，跳过")
                    } else {
                        Log.d("ScanAudio", "文件 ${file.displayName} 准备上传, 手机号=$phoneNumber")
                    }

                    needUpload && hasPhone
                }

                // 4️⃣ 加入 _audioFiles
                _audioFiles.addAll(uploadFiles)
                Log.d("ScanAudio", "最终准备上传的文件数量: ${_audioFiles.size}")

                // 5️⃣ 上传
                _audioFiles.forEachIndexed { index, file ->
                    pushFile(file)
                    progress = index + 1
                    Log.d("ScanAudio", "上传进度: $progress / ${_audioFiles.size}")
                }

            } catch (e: Exception) {
                Log.e("ScanAudio", "扫描或验证异常: ${e.message}", e)
            } finally {
                isScanning = false
            }
        }
    }

    // 上传单个文件
    fun pushFile(file: AudioFile) {
        val phoneNumber = extractPhoneNumber(file.displayName) ?: run {
            Log.d("ScanAudio", "文件 ${file.displayName} 没有手机号，跳过上传")
            return
        }

        val callRecord = CallRecord(
            phoneNumber = phoneNumber,
            startTime = Date(file.dateAdded - file.duration),
            endTime = Date(file.dateAdded),
            duration = file.duration / 1000,
            status = CallStatus.COMPLETED,
            audioFileName = file.displayName,
            audioFileUri = file.filePath
        )

        CallRecordManager.uploadCallRecord(callRecord)
        Log.d("ScanAudio", "上传文件 ${file.displayName} 成功")
    }

    // 正则提取手机号
    fun extractPhoneNumber(fileName: String): String? {
        val regex = Regex("""1[3-9]\d{9}""")
        return regex.find(fileName)?.value
    }

    /**
     * 刷新数据（使用相同的请求参数）
     */
    fun refresh() {
        loadCallRecords(_selectedTimeRange.value)
    }

    /**
     * 清除错误状态
     */
    fun clearError() {
        _errorMessage.value = null
    }
}