package com.mybus17000.ui.screens

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mybus17000.data.BusRoute
import com.mybus17000.data.BusSegment
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import java.time.LocalDateTime

class RouteViewModel : ViewModel() {

    private val _routes = MutableStateFlow<List<BusRoute>>(emptyList())
    val routes: StateFlow<List<BusRoute>> = _routes

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

    private val _error = MutableStateFlow<String?>(null)
    val error: StateFlow<String?> = _error

    fun searchRoutes(from: String, to: String, dateTime: LocalDateTime?, isArrival: Boolean) {
        viewModelScope.launch {
            try {
                _isLoading.value = true
                _error.value = null

                // simulation
                delay(800)

                val route1 = BusRoute(
                    totalDuration = 32,
                    numberOfChanges = 1,
                    segments = listOf(
                        BusSegment("Ligne 4", "Gare", "Place des Capucins", "08:10", "08:25"),
                        BusSegment("Ligne 12", "Place des Capucins", "Vieux-Port", "08:28", "08:42")
                    )
                )

                val route2 = BusRoute(
                    totalDuration = 41,
                    numberOfChanges = 0,
                    segments = listOf(
                        BusSegment("Ligne 8", "Gare", "Vieux-Port", "08:05", "08:46")
                    )
                )

                _routes.value = listOf(route1, route2)

            } catch (e: Exception) {
                _error.value = e.message
            } finally {
                _isLoading.value = false
            }
        }
    }
}