import useStateSubscriber from "@racletteOrchestrator/composables/useStateSubscriber"
import type { Composition } from "@shared/types/core/Composition.types"
import { getCompositionPathById } from "@racletteCore/store/reducers/compositions/selectors"
import { computed } from "vue"
import { DEFAULT_SLOT_NAME } from "@racletteOrchestrator/router/routeParserHelper"

// Simple reference cache to prevent unnecessary re-renders
let cachedCompositionId: string | null = null
let cachedTitle: string | null = null
let cachedWidgetsLayout: any = null

export const useCurrentComposition = (key: string = DEFAULT_SLOT_NAME) => {
  const { state: currentComposableId } = useStateSubscriber(["ui", key])
  const { state: compositions } = useStateSubscriber("compositions")

  const state = computed<Composition | undefined>(() => {
    return compositions.value[currentComposableId.value]
  })

  const id = computed(() => state.value?._id)
  const slotLayout = computed(() => state.value?.slotLayout || "default")

  const localizedPath = computed(() =>
    id.value ? getCompositionPathById(id.value) : undefined,
  )

  const title = computed(() => state.value?.title)
  const description = computed(() => state.value?.description)
  const tags = computed(() => state.value?.tags ?? [])
  const icon = computed(() => state.value?.icon)
  const pathname = computed(() => state.value?.pathname)
  const status = computed(() => state.value?.status)

  // Cached widgetsLayout that only updates when core composition changes
  const widgetsLayout = computed(() => {
    const currentComposition = state.value
    if (!currentComposition || !currentComposition._id) {
      return undefined
    }

    const compositionId = currentComposition._id
    const currentTitle = currentComposition.title
    const currentWidgetsLayout = currentComposition.widgetsLayout

    // If composition ID or title changed, it's a different composition - update cache
    if (cachedCompositionId !== compositionId || cachedTitle !== currentTitle) {
      cachedCompositionId = compositionId
      cachedTitle = currentTitle
      cachedWidgetsLayout = currentWidgetsLayout
      return currentWidgetsLayout
    }

    // Same composition, return cached reference to prevent re-renders
    return cachedWidgetsLayout
  })

  return {
    state,
    id,
    localizedPath,
    title,
    description,
    tags,
    icon,
    pathname,
    status,
    widgetsLayout,
    slotLayout,
  }
}

export default useCurrentComposition
