import type { GridApi } from 'ag-grid-community'
import { onActivated, onBeforeUnmount, onMounted, watch, type Ref, type WatchSource } from 'vue'

type AsyncTask = () => Promise<void> | void

export const usePricingPaneLifecycle = <TRow>(options: {
  gridApi: Ref<GridApi<TRow> | null>
  loadFromIndexedDB: () => Promise<void>
  syncLinkedFields: () => Promise<void>
  linkedSourceSignature: WatchSource<unknown>
  linkedSecondarySignature?: WatchSource<unknown>
  syncSecondaryLinkedFields?: AsyncTask
  saveToIndexedDB: AsyncTask
}) => {
  const hydratePane = async () => {
    await options.loadFromIndexedDB()
    await options.syncLinkedFields()
  }

  let skipNextActivated = false

  onMounted(async () => {
    skipNextActivated = true
    await hydratePane()
  })

  onActivated(async () => {
    if (skipNextActivated) {
      skipNextActivated = false
      return
    }
    await hydratePane()
  })

  onBeforeUnmount(() => {
    options.gridApi.value?.stopEditing()
    options.gridApi.value = null
    void options.saveToIndexedDB()
  })

  watch(options.linkedSourceSignature, () => {
    void options.syncLinkedFields()
  })

  if (options.linkedSecondarySignature && options.syncSecondaryLinkedFields) {
    watch(options.linkedSecondarySignature, () => {
      void options.syncSecondaryLinkedFields?.()
    })
  }
}

export const usePricingScalePaneLifecycle = usePricingPaneLifecycle
