import { RouteDto } from '@/proxy/routes'
import React, { createContext, useContext, useEffect, useState } from 'react'
import { useStoreState } from '@/store/store'

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 extraProperties = useStoreState((state) => state.abpConfig?.config?.extraProperties)
  const [routes, setRoutes] = useState<RouteDto[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const loadRoutesFromConfig = () => {
    setLoading(true)
    setError(null)

    try {
      // Get routes from extraProperties instead of API call
      const configRoutes = extraProperties?.routes as RouteDto[]
      
      if (configRoutes && Array.isArray(configRoutes)) {
        setRoutes(configRoutes)
      } else {
        setRoutes([])
        setError('No routes found in configuration')
      }
    } catch (e: any) {
      setError(e.message || 'Error loading routes from configuration')
      setRoutes([])
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (extraProperties) {
      loadRoutesFromConfig()
    }
  }, [extraProperties])

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