// ui/pipeline/PipelineViewModel.kt
package com.example.initiateaphonecallapp.ui.pipeline

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.initiateaphonecallapp.data.model.PipelineResponse
import com.example.initiateaphonecallapp.data.repository.PiplineRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class PipelineViewModel : ViewModel() {
    private val repository = PiplineRepository()

    private val _pipelines = MutableStateFlow<List<PipelineResponse>>(emptyList())
    val pipelines: StateFlow<List<PipelineResponse>> = _pipelines.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 _isAutoDialing = MutableStateFlow(false)
    val isAutoDialing: StateFlow<Boolean> = _isAutoDialing.asStateFlow()

    private val _currentDialingIndex = MutableStateFlow(0)
    val currentDialingIndex: StateFlow<Int> = _currentDialingIndex.asStateFlow()

    // 获取可拨打的管道列表（status为0或1）
    val dialablePipelines: List<PipelineResponse>
        get() = _pipelines.value.filter { it.status == 0 || it.status == 1 }

    init {
        loadPipelines()
    }

    fun loadPipelines() {
        viewModelScope.launch {
            _isLoading.value = true
            _errorMessage.value = null

            val result = repository.getPipelines()
            result.onSuccess { pipelineList ->
                _pipelines.value = pipelineList
            }.onFailure { exception ->
                _errorMessage.value = "加载失败: ${exception.message}"
            }

            _isLoading.value = false
        }
    }

    fun clearError() {
        _errorMessage.value = null
    }

    fun updatePipelineStatus(pipelineId: String, newStatus: Int) {
        val updatedList = _pipelines.value.map { pipeline ->
            if (pipeline.id == pipelineId) {
                pipeline.copy(status = newStatus)
            } else {
                pipeline
            }
        }
        _pipelines.value = updatedList
    }

    // 自动拨号控制
    fun startAutoDial() {
        _isAutoDialing.value = true
        _currentDialingIndex.value = 0
    }

    fun stopAutoDial() {
        _isAutoDialing.value = false
        _currentDialingIndex.value = 0
    }

    fun updateDialingIndex(index: Int) {
        _currentDialingIndex.value = index
    }

    // 注册广播接收器来监听自动拨号状态
    fun registerAutoDialReceiver(context: Context) {
        val filter = IntentFilter().apply {
            addAction("AUTO_DIAL_STOPPED")
            addAction("AUTO_DIAL_NEXT")
        }
        context.registerReceiver(autoDialReceiver, filter, Context.RECEIVER_NOT_EXPORTED)
    }

    fun unregisterAutoDialReceiver(context: Context) {
        try {
            context.unregisterReceiver(autoDialReceiver)
        } catch (e: IllegalArgumentException) {
            // 接收器未注册，忽略错误
        }
    }

    private val autoDialReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            when (intent?.action) {
                "AUTO_DIAL_STOPPED" -> {
                    stopAutoDial()
                }
                "AUTO_DIAL_NEXT" -> {
                    val index = intent.getIntExtra("current_index", 0)
                    updateDialingIndex(index)
                }
            }
        }
    }
}