import {
  getCompositionPathById,
  getLocalizedName,
} from "@racletteCore/store/reducers/compositions/selectors"
import useInteractionLinks from "@racletteOrchestrator/composables/useInteractionLinks"
import { computed } from "vue"
import useRouteState from "./useRouteState"
import useUiState from "@racletteOrchestrator/composables/useUiState"

export type NavigationItem = {
  icon: string
  route?: string
  sortOrder: number
  compositionId: string
  title: string
  slotType: string
  navigateTo: () => void
}

export default () => {
  const { locale } = useUiState()
  const { state } = useInteractionLinks([
    "page-navigation",
    "user-menu",
    "app-bar",
  ])
  const { triggerInteractionLink } = useRouteState()

  const navigationItems = computed<{
    navigationItems: NavigationItem[]
    footerItems: NavigationItem[]
    userMenuItems: NavigationItem[]
    appBarItems: NavigationItem[]
  }>(() => {
    const navigationItems: NavigationItem[] = []
    const footerItems: NavigationItem[] = []
    const userMenuItems: NavigationItem[] = []
    const appBarItems: NavigationItem[] = []
    locale.value
    state.value.forEach((interactionLink) =>
      interactionLink.triggers

        .sort(
          (a, b) => (a.settings.sortOrder ?? 0) - (b.settings.sortOrder ?? 0),
        )
        .forEach((trigger) => {
          if (trigger.settings) {
            const { type, settings } = trigger
            const { icon, title, sortOrder, navigationBarType } = settings

            const item: NavigationItem = {
              icon,
              sortOrder,
              compositionId: interactionLink.composition,
              title: getLocalizedName(title),
              route: getCompositionPathById(interactionLink.composition),
              slotType: interactionLink.slotType,
              navigateTo: () => triggerInteractionLink(interactionLink),
            }

            if (type === "page-navigation") {
              if (navigationBarType === "footerItem") {
                footerItems.push(item)
              } else {
                navigationItems.push(item)
              }
            } else if (type === "user-menu") {
              userMenuItems.push(item)
            } else if (type === "app-bar") {
              appBarItems.push(item)
            }
          }
        }),
    )

    return {
      navigationItems,
      footerItems,
      userMenuItems,
      appBarItems,
    }
  })
  return {
    state: navigationItems,
  }
}
