type ModalComponent = any
type ModalProps = Record<string, any> | undefined

const modalStack = useState<any[]>('__fed_modal_stack__', () => [])

export const useModal = () => {
  const overlay = useOverlay()

  const open = (component: ModalComponent, props?: ModalProps) => {
    const instance = overlay.create(component, { props, destroyOnClose: true })
    modalStack.value.push(instance)

    const result = instance.open(props)
    result.finally(() => {
      modalStack.value = modalStack.value.filter((entry) => entry.id !== instance.id)
    })

    return result
  }

  const close = (value?: any) => {
    const current = modalStack.value[modalStack.value.length - 1]

    if (!current) {
      return
    }

    current.close(value)
  }

  return {
    open,
    close
  }
}
