import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'

export function useQueryMode(key: string = 'mode') {
  const route = useRoute()
  const router = useRouter()

  const mode = computed<'list' | 'add'>({
    get: () => (route.query[key] && route.query[key] === 'add' ? 'add' : 'list'),
    set: (val) => {
      router.replace({
        path: route.path,
        query: {
          ...route.query,
          [key]: val === 'list' ? undefined : val,
        },
      })
    },
  })

  const openForm = () => (mode.value = 'add')
  const backToList = () => (mode.value = 'list')

  return { mode, openForm, backToList }
}
