import React from 'react'
import { useRouter } from 'next/navigation'
import useNavigationStore from '@/app/store/navigationStore'
import type { NavigationStore } from '@/app/store/navigationStore'
 
export enum MainRoutes {
  DASHBOARD = '/dashboard',
  NAVIGATION = '/navigation', 
  ALERTS = '/alerts',
  REPORTS = '/reports',
  OBJECTS = '/objects'
}

export const SIDEBAR_ITEM_MAP = { 
  1: { type: 'route', value: MainRoutes.DASHBOARD },
  2: { type: 'route', value: MainRoutes.NAVIGATION },
  8: { type: 'route', value: MainRoutes.ALERTS },
  9: { type: 'route', value: MainRoutes.REPORTS }
} as const

export class NavigationService {
  private router!: ReturnType<typeof useRouter>
  private navigationStore!: NavigationStore
  private initialized = false
   
  init(router: ReturnType<typeof useRouter>, navigationStore: NavigationStore) {
    if (this.initialized) {
      return // Предотвращаем повторную инициализацию
    }
    this.router = router
    this.navigationStore = navigationStore
    this.initialized = true
  }
  
  isInitialized(): boolean {
    return this.initialized
  }
   
  navigateToRoute(route: MainRoutes) {  
    // Убираем подменю перед переходом на другую страницу
    if (route !== MainRoutes.NAVIGATION) {
      this.navigationStore.setCurrentSubmenu(null)
    }
    
    this.router.push(route)
  }
   
  handleSidebarItemClick(itemId: number, currentPath: string): boolean { 
    if (!this.initialized) {
      console.error('NavigationService not initialized!')
      return false
    }
    
    const mapping = SIDEBAR_ITEM_MAP[itemId as keyof typeof SIDEBAR_ITEM_MAP]
    
    if (!mapping) { 
      return false  
    }
     
    if (mapping.type === 'route') {  
      this.navigateToRoute(mapping.value as MainRoutes)
      return true
    }
     
    return false
  }
 
  goBack() {
    this.navigationStore.goBack()
  }
 
  selectObjectAndGoToDashboard(objectId: string, objectTitle: string) {
    this.navigationStore.setCurrentObject(objectId, objectTitle)
    // Проверяем, что подменю закрыто перед навигацией
    this.navigationStore.setCurrentSubmenu(null)
    const url = `${MainRoutes.DASHBOARD}?objectId=${encodeURIComponent(objectId)}&objectTitle=${encodeURIComponent(objectTitle)}`
    this.router.push(url)
  }
}
  
export const navigationService = new NavigationService()
 
export function useNavigationService() {
  const router = useRouter()
  const navigationStore = useNavigationStore()
     
  React.useMemo(() => {
    if (!navigationService.isInitialized()) { 
      navigationService.init(router, navigationStore)
    }
  }, [router, navigationStore])
  
  return navigationService
}