package com.rugvedsarika.landarea.ui

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import com.rugvedsarika.landarea.data.ConversionRecord
import com.rugvedsarika.landarea.data.HistoryDatabase
import com.rugvedsarika.landarea.logic.AreaConverter
import kotlinx.coroutines.launch
import java.util.Locale

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

    private val db = HistoryDatabase.getDatabase(application)
    private val historyDao = db.historyDao()

    // --- Converter State ---
    private val _inputValue = MutableLiveData<String>("")
    val inputValue: LiveData<String> = _inputValue

    private val _fromUnit = MutableLiveData<String>("Square Meter (m²)")
    val fromUnit: LiveData<String> = _fromUnit

    private val _toUnit = MutableLiveData<String>("Square Foot (ft²)")
    val toUnit: LiveData<String> = _toUnit

    private val _selectedState = MutableLiveData<String>("Standard")
    val selectedState: LiveData<String> = _selectedState

    private val _result = MutableLiveData<String>("0.0")
    val result: LiveData<String> = _result

    val units: List<String> = AreaConverter.getAllUnits()
    val states: List<String> = AreaConverter.getAllStates()

    // --- History State ---
    val history: LiveData<List<ConversionRecord>> = historyDao.getAllHistory().asLiveData()

    fun onInputValueChanged(newValue: String) {
        _inputValue.value = newValue
        calculateConversion()
    }

    fun onFromUnitChanged(unit: String) {
        _fromUnit.value = unit
        calculateConversion()
    }

    fun onToUnitChanged(unit: String) {
        _toUnit.value = unit
        calculateConversion()
    }

    fun onStateChanged(state: String) {
        _selectedState.value = state
        calculateConversion()
    }

    fun swapUnits() {
        val currentFrom = _fromUnit.value ?: "Square Meter (m²)"
        val currentTo = _toUnit.value ?: "Square Foot (ft²)"
        _fromUnit.value = currentTo
        _toUnit.value = currentFrom
        calculateConversion()
    }

    private fun calculateConversion() {
        val input = _inputValue.value?.toDoubleOrNull()
        if (input == null) {
            _result.value = "0.0"
            return
        }

        val from = _fromUnit.value ?: return
        val to = _toUnit.value ?: return
        val state = _selectedState.value ?: "Standard"

        val convertedValue = AreaConverter.convert(input, from, to, state)
        val resultStr = String.format(Locale.getDefault(), "%.4f", convertedValue)
        _result.value = resultStr
        
        // Auto-save to history (debounced or after some time in a real app, here we just save)
        saveHistory(input.toString(), from, to, resultStr, "Converter")
    }

    private fun saveHistory(input: String, from: String, to: String, result: String, type: String) {
        viewModelScope.launch {
            historyDao.insertRecord(
                ConversionRecord(
                    timestamp = System.currentTimeMillis(),
                    inputValue = input,
                    fromUnit = from,
                    toUnit = to,
                    result = result,
                    type = type
                )
            )
        }
    }

    fun clearHistory() {
        viewModelScope.launch {
            historyDao.clearHistory()
        }
    }
}
