import { Ref, useEffect } from 'react'

import { useBodyScrollLock } from '../core'

/** State management for nested modals. */
class ModalManager {
  modals: any[] = []

  add = (modal: any) => this.modals.push(modal)

  remove = (modal: any) => (this.modals = this.modals.filter(m => m !== modal))

  isTopModal = (modal: any) => {
    const topmostModal = this.modals[this.modals.length - 1]
    return topmostModal === modal
  }
}

export const manager = new ModalManager()

/** Refs of new modals will be automatically added/removed from the state when rendering. */
export function useModalManager(ref: Ref<any>, isOpen?: boolean, disableScrollLock?: boolean) {
  const { setIsScrollLocked } = useBodyScrollLock()
  useEffect(() => {
    if (isOpen) {
      manager.add(ref)
      if (!disableScrollLock) setIsScrollLocked(true)
    }

    return () => {
      manager.remove(ref)
      if (!disableScrollLock) setIsScrollLocked(false)
    }
  }, [isOpen, ref])
}
