package com.manalejandro.odb2bluetooth.ui.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.manalejandro.odb2bluetooth.data.database.ObdDatabase
import com.manalejandro.odb2bluetooth.data.database.dto.SignalDto
import com.manalejandro.odb2bluetooth.data.database.dto.VehicleDto
import com.manalejandro.odb2bluetooth.data.repository.ObdRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * ViewModel for vehicle selection and signal browsing
 */
class VehicleViewModel(application: Application) : AndroidViewModel(application) {

    private val database = ObdDatabase.getDatabase(application)
    private val repository = ObdRepository(
        database.vehicleDao(),
        database.obdSignalDao(),
        database.dtcCodeDao()
    )

    private val _vehicles = MutableStateFlow<List<VehicleDto>>(emptyList())
    val vehicles: StateFlow<List<VehicleDto>> = _vehicles

    private val _selectedVehicle = MutableStateFlow<VehicleDto?>(null)
    val selectedVehicle: StateFlow<VehicleDto?> = _selectedVehicle

    private val _signals = MutableStateFlow<List<SignalDto>>(emptyList())
    val signals: StateFlow<List<SignalDto>> = _signals

    private val _searchQuery = MutableStateFlow("")
    val searchQuery: StateFlow<String> = _searchQuery

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

    init {
        loadVehicles()
    }

    /**
     * Load all vehicles from database
     */
    private fun loadVehicles() {
        viewModelScope.launch {
            _isLoading.value = true
            repository.getAllVehicles().collectLatest { vehicleList ->
                _vehicles.value = vehicleList
                _isLoading.value = false
            }
        }
    }

    /**
     * Search vehicles by query
     */
    fun searchVehicles(query: String) {
        _searchQuery.value = query
        viewModelScope.launch {
            _isLoading.value = true
            if (query.isBlank()) {
                repository.getAllVehicles().collectLatest { vehicleList ->
                    _vehicles.value = vehicleList
                    _isLoading.value = false
                }
            } else {
                repository.searchVehicles(query).collectLatest { vehicleList ->
                    _vehicles.value = vehicleList
                    _isLoading.value = false
                }
            }
        }
    }

    /**
     * Select a vehicle and load its signals
     */
    fun selectVehicle(vehicle: VehicleDto) {
        _selectedVehicle.value = vehicle
        loadSignalsForVehicle(vehicle.modelId)
    }

    /**
     * Clear vehicle selection
     */
    fun clearSelection() {
        _selectedVehicle.value = null
        _signals.value = emptyList()
    }

    /**
     * Load signals for a specific vehicle
     */
    private fun loadSignalsForVehicle(modelId: Int) {
        viewModelScope.launch {
            _isLoading.value = true
            repository.getSignalsByModel(modelId).collectLatest { signalList ->
                _signals.value = signalList
                _isLoading.value = false
            }
        }
    }
}

