package com.example.initiateaphonecallapp.ui.calllog

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.initiateaphonecallapp.data.model.CallRecord
import com.example.initiateaphonecallapp.data.model.CallRecordRequest
import com.example.initiateaphonecallapp.data.repository.CallLogRepository
import com.example.initiateaphonecallapp.manager.AudioPlayManager
import com.example.initiateaphonecallapp.utils.TimeRangeUtils
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.time.LocalDateTime

 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()
     /**
      * 播放音频
      */
     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
        }
    }

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

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