package com.example.livingai.pages.addprofile

import android.content.Context
import android.net.Uri
import android.provider.OpenableColumns
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.livingai.domain.model.AnimalDetails
import com.example.livingai.domain.usecases.GetAnimalDetails
import com.example.livingai.domain.usecases.ProfileEntry.ProfileEntryUseCase
import com.example.livingai.utils.CoroutineDispatchers
import com.example.livingai.utils.IdGenerator
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class AddProfileViewModel(
    private val profileEntryUseCase: ProfileEntryUseCase,
    private val getAnimalDetails: GetAnimalDetails,
    private val dispatchers: CoroutineDispatchers,
    private val context: Context,
    val savedStateHandle: SavedStateHandle? = null
) : ViewModel() {
    
    private val _animalDetails = mutableStateOf<AnimalDetails?>(null)
    val animalDetails: State<AnimalDetails?> = _animalDetails

    private val _currentAnimalId = mutableStateOf<String?>(null)
    val currentAnimalId: State<String?> = _currentAnimalId
    
    // UI State
    var species = mutableStateOf<String?>(null)
    var breed = mutableStateOf<String?>(null)
    var age = mutableStateOf("")
    var milkYield = mutableStateOf("")
    var calvingNumber = mutableStateOf("")
    var reproductiveStatus = mutableStateOf<String?>(null)
    var description = mutableStateOf("")

    // Errors
    var ageError = mutableStateOf<String?>(null)
    var milkYieldError = mutableStateOf<String?>(null)
    var calvingNumberError = mutableStateOf<String?>(null)
    var speciesError = mutableStateOf<String?>(null)
    var breedError = mutableStateOf<String?>(null)
    var reproductiveStatusError = mutableStateOf<String?>(null)
    
    // Save state
    private val _saveSuccess = mutableStateOf(false)
    val saveSuccess: State<Boolean> = _saveSuccess
    
    // State for photos and video
    val photos = mutableStateMapOf<String, String>()
    private val _videoUri = mutableStateOf<String?>(null)
    val videoUri: State<String?> = _videoUri

    fun loadAnimal(animalId: String?) {
        if (animalId == null) {
            val newId = IdGenerator.generateAnimalId()
            _currentAnimalId.value = newId
            _animalDetails.value = null
            
            // Reset UI State
            species.value = null
            breed.value = null
            age.value = ""
            milkYield.value = ""
            calvingNumber.value = ""
            reproductiveStatus.value = null
            description.value = ""
            clearErrors()
            
            photos.clear()
            _videoUri.value = null
        } else {
            _currentAnimalId.value = animalId
            profileEntryUseCase.getAnimalDetails(animalId).onEach { details ->
                if (details != null) {
                    _animalDetails.value = details
                    
                    // Populate UI State
                    species.value = details.species.ifBlank { null }
                    breed.value = details.breed.ifBlank { null }
                    age.value = if (details.age == 0) "" else details.age.toString()
                    milkYield.value = if (details.milkYield == 0) "" else details.milkYield.toString()
                    calvingNumber.value = if (details.calvingNumber == 0) "" else details.calvingNumber.toString()
                    reproductiveStatus.value = details.reproductiveStatus.ifBlank { null }
                    description.value = details.description
                    clearErrors()
                    
                    // Populate photos
                    photos.clear()
                    // Process images on IO thread as it may involve DB queries
                    withContext(dispatchers.io) {
                        val photoMap = mutableMapOf<String, String>()
                        details.images.forEach { path ->
                             val uri = Uri.parse(path)
                             val filename = getFileName(uri) ?: path.substringAfterLast('/')
                             val nameWithoutExt = filename.substringBeforeLast('.')
                             val parts = nameWithoutExt.split('_')
                             if (parts.size >= 2) {
                                 val orientation = parts.last()
                                 photoMap[orientation] = path
                             }
                        }
                        withContext(dispatchers.main) {
                            photoMap.forEach { (k, v) -> photos[k] = v }
                        }
                    }
                    _videoUri.value = details.video.ifBlank { null }
                }
            }.launchIn(viewModelScope)
        }
    }

    private fun clearErrors() {
        ageError.value = null
        milkYieldError.value = null
        calvingNumberError.value = null
        speciesError.value = null
        breedError.value = null
        reproductiveStatusError.value = null
    }
    
    private fun getFileName(uri: Uri): String? {
        var result: String? = null
        if (uri.scheme == "content") {
            val cursor = context.contentResolver.query(uri, null, null, null, null)
            try {
                if (cursor != null && cursor.moveToFirst()) {
                    val index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                    if (index >= 0) {
                        result = cursor.getString(index)
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                cursor?.close()
            }
        }
        if (result == null) {
            result = uri.path
            val cut = result?.lastIndexOf('/')
            if (cut != null && cut != -1) {
                result = result?.substring(cut + 1)
            }
        }
        return result
    }

    fun addPhoto(orientation: String, uri: String) {
        photos[orientation] = uri
    }
    
    fun setVideo(uri: String) {
        _videoUri.value = uri
    }

    fun validateInputs(): Boolean {
        var isValid = true
        
        if (species.value.isNullOrBlank()) {
            speciesError.value = "Species is required"
            isValid = false
        } else {
            speciesError.value = null
        }

        if (breed.value.isNullOrBlank()) {
            breedError.value = "Breed is required"
            isValid = false
        } else {
            breedError.value = null
        }

        if (reproductiveStatus.value.isNullOrBlank()) {
            reproductiveStatusError.value = "Status is required"
            isValid = false
        } else {
            reproductiveStatusError.value = null
        }
        
        val ageInt = age.value.toIntOrNull()
        if (ageInt == null || ageInt < 0) {
            ageError.value = "Invalid age"
            isValid = false
        } else {
             ageError.value = null
        }
        
        val milkInt = milkYield.value.toIntOrNull()
        if (milkInt == null || milkInt < 0) {
            milkYieldError.value = "Invalid milk yield"
            isValid = false
        } else {
            milkYieldError.value = null
        }
        
        val calvingInt = calvingNumber.value.toIntOrNull()
        if (calvingInt == null || calvingInt < 0) {
            calvingNumberError.value = "Invalid calving number"
            isValid = false
        } else {
             calvingNumberError.value = null
        }
        
        return isValid
    }

    fun saveAnimalDetails() {
        if (!validateInputs()) return

        val id = _currentAnimalId.value ?: IdGenerator.generateAnimalId().also { _currentAnimalId.value = it }
        
        val details = AnimalDetails(
            animalId = id,
            species = species.value ?: "",
            breed = breed.value ?: "",
            age = age.value.toIntOrNull() ?: 0,
            milkYield = milkYield.value.toIntOrNull() ?: 0,
            calvingNumber = calvingNumber.value.toIntOrNull() ?: 0,
            reproductiveStatus = reproductiveStatus.value ?: "",
            description = description.value,
            images = photos.values.toList(),
            video = _videoUri.value ?: "",
            name = "", sex = "", weight = 0 
        )

        viewModelScope.launch {
            profileEntryUseCase.setAnimalDetails(details)
            _saveSuccess.value = true
        }
    }
    
    fun onSaveComplete() {
        _saveSuccess.value = false
    }

    init {
        // Try to auto-load when editing via saved state handle
        val animalId: String? = savedStateHandle?.get<String>("animalId")
        // Call loadAnimal unconditionally to ensure ID generation for new profiles
        loadAnimal(animalId)
    }
}
