'use client'

import { createContext, useContext, useCallback, type ReactNode } from 'react'
import type { BrainfishCollection, BrainfishRESTRequest } from './types'

interface NavigationContextValue {
  /** Navigate to an endpoint by operationId or ID */
  navigateToEndpoint: (operationIdOrId: string) => void
  /** Current collection */
  collection: BrainfishCollection | null
}

const NavigationContext = createContext<NavigationContextValue | null>(null)

interface NavigationProviderProps {
  children: ReactNode
  collection: BrainfishCollection | null
  onSelectRequest: (request: BrainfishRESTRequest) => void
}

/**
 * Helper to find request by operationId (name) or ID in collection
 */
function findRequestByOperationIdOrId(
  collection: BrainfishCollection,
  operationIdOrId: string
): BrainfishRESTRequest | null {
  // Normalize the search term (handle both snake_case and the formatted name)
  const normalizedSearch = operationIdOrId.toLowerCase().replace(/[\s-]/g, '_')
  
  // Check direct requests
  for (const request of collection.requests) {
    // Check by ID
    if (request.id === operationIdOrId) return request
    // Check by name (operationId) - exact match
    if (request.name.toLowerCase().replace(/[\s-]/g, '_') === normalizedSearch) return request
    // Check by name - partial match (for formatted names like "Post Carts" -> "post_carts")
    const requestNameNormalized = request.name.toLowerCase().replace(/[\s-]/g, '_')
    if (requestNameNormalized === normalizedSearch) return request
  }
  
  // Check folders recursively
  for (const folder of collection.folders) {
    const request = findRequestByOperationIdOrId(folder, operationIdOrId)
    if (request) return request
  }
  
  return null
}

export function NavigationProvider({ 
  children, 
  collection, 
  onSelectRequest 
}: NavigationProviderProps) {
  const navigateToEndpoint = useCallback((operationIdOrId: string) => {
    if (!collection) {
      console.warn('[Navigation] No collection available')
      return
    }
    
    const request = findRequestByOperationIdOrId(collection, operationIdOrId)
    if (request) {
      console.log('[Navigation] Navigating to endpoint:', request.name)
      onSelectRequest(request)
    } else {
      console.warn('[Navigation] Endpoint not found:', operationIdOrId)
    }
  }, [collection, onSelectRequest])
  
  return (
    <NavigationContext.Provider value={{ navigateToEndpoint, collection }}>
      {children}
    </NavigationContext.Provider>
  )
}

export function useNavigation() {
  const context = useContext(NavigationContext)
  if (!context) {
    // Return a no-op function if not in provider (for backwards compatibility)
    return {
      navigateToEndpoint: () => {},
      collection: null
    }
  }
  return context
}
