import { RouteDto } from '@/proxy/routes'
import { RouteService } from '@/services/route.service'
import React, { createContext, useContext, useEffect, useState } from 'react'

interface DynamicRoutesContextProps {
  routes: RouteDto[]
  loading: boolean
  error: string | null
  reload: () => void
}

const DynamicRoutesContext = createContext<DynamicRoutesContextProps | undefined>(undefined)

export const useDynamicRoutes = () => {
  const ctx = useContext(DynamicRoutesContext)
  if (!ctx) throw new Error('useDynamicRoutes must be used within DynamicRoutesProvider')
  return ctx
}

export const DynamicRoutesProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [routes, setRoutes] = useState<RouteDto[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const fetchRoutes = async () => {
    setLoading(true)
    setError(null)

    try {
      const routeService = new RouteService()
      const res = await routeService.getRoutes()

      if (res.data) {
        setRoutes(res.data)
      } else {
        throw new Error('No routes found')
      }
    } catch (e: any) {
      setError(e.message || 'Unknown error')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchRoutes()
  }, [])

  return (
    <DynamicRoutesContext.Provider value={{ routes, loading, error, reload: fetchRoutes }}>
      {children}
    </DynamicRoutesContext.Provider>
  )
}
