/** Pinia store for route management */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Route, BusStop } from '@/types'
import { routesService } from '@/services/routesService'

export const useRouteStore = defineStore('route', () => {
    const selectedRouteId = ref<string | null>(null)
    const selectedRouteName = ref<string | null>(null)
    const selectedRouteStops = ref<BusStop[]>([])
    const allRoutes = ref<Route[]>([])
    const isLoadingRoutes = ref(false)
    const isLoadingStops = ref(false)
    const error = ref<string | null>(null)

    const hasSelectedRoute = computed(() => selectedRouteId.value !== null && selectedRouteName.value !== null)

    async function loadRoutes(filters?: { originCity?: string, destinationCity?: string }, force = false) {
        if (!force && !filters && allRoutes.value.length > 0) {
            return
        }

        isLoadingRoutes.value = true
        error.value = null
        try {
            allRoutes.value = await routesService.getAllRoutes(filters)
        } catch (e) {
            error.value = e instanceof Error ? e.message : 'Failed to load routes'
            console.error('Error loading routes:', e)
        } finally {
            isLoadingRoutes.value = false
        }
    }

    async function loadRouteStops(routeId: string) {
        isLoadingStops.value = true
        error.value = null
        try {
            selectedRouteStops.value = await routesService.getRouteStops(routeId)
        } catch (e) {
            error.value = e instanceof Error ? e.message : 'Failed to load route stops'
            console.error('Error loading route stops:', e)
            selectedRouteStops.value = []
        } finally {
            isLoadingStops.value = false
        }
    }

    async function selectRoute(routeId: string, routeName: string) {
        if (selectedRouteId.value === routeId) return
        selectedRouteId.value = routeId
        selectedRouteName.value = routeName
        selectedRouteStops.value = [] // Clear old stops immediately
        await loadRouteStops(routeId)
    }

    function clearSelection() {
        selectedRouteId.value = null
        selectedRouteName.value = null
        selectedRouteStops.value = []
    }

    return {
        selectedRouteId,
        selectedRouteName,
        selectedRouteStops,
        allRoutes,
        isLoadingRoutes,
        isLoadingStops,
        error,
        hasSelectedRoute,
        loadRoutes,
        loadRouteStops,
        selectRoute,
        clearSelection,
    }
})

