// eslint-disable-next-line no-unused-vars
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

// import { defineAsyncComponent } from 'vue'

import { setupLayouts } from 'virtual:generated-layouts'
import generatedRoutes from 'virtual:generated-pages'
// import generatedRoutes from 'pages-generated'
// import { setupLayouts } from 'layouts-generated'

import useState from '~/hooks/useState'

// const Login = defineAsyncComponent(() => import('./views/Login.vue'))
import store from '~/store'

import Home from '~/views/Home.vue'
// import Register from '~/views/auth/Register.vue'
import Login from '~/views/Login.vue'
import Logout from '~/views/Logout.vue'

import { verify_auth, check_credentials } from '~/hooks/utils'
// import {
//   lang_url,
//   req_lang,
// } from '~/defs/ta_defs'
// const DataGrid = () => import('~/views/DataGrid.vue')
//const SambaModel = () => import('~/views/SambaModel.vue')

const layoutsRoutes = setupLayouts(generatedRoutes)
/*
// import routes generated by Voie
import pgRoutes from 'voie-pages'

const UIElements = defineAsyncComponent(() => import('./views/UIElements.vue'))
const Tables = defineAsyncComponent(() => import('./views/Tables.vue'))
const Dashboard = defineAsyncComponent(() => import('./views/Dashboard.vue'))
const Forms = defineAsyncComponent(() => import('./views/Forms.vue'))
const Input = defineAsyncComponent(() => import('./views/Input.vue'))
const Home = defineAsyncComponent(() => import('./views/Home.vue'))
const Modal = defineAsyncComponent(() => import('./views/Modal.vue'))
const Blank = defineAsyncComponent(() => import('./views/Blank.vue'))
const OLogin = defineAsyncComponent(() => import('./views/OLogin.vue'))
const Entry = defineAsyncComponent(() => import('./views/Entry.vue'))
*/

// https://medium.com/swlh/adding-meta-fields-and-transitions-to-vue-router-routes-f5cb78a7ed97
// router.beforeEach((to, from, next) => {
//   if (to.meta.requireAuth) {
//     if (!localStorage.getItem("auth")) {
//       next('/notfound')
//     } else {
//       next();
//     }
//   } else {
//     next();
//   }
// });

// const get_lang = (_to: any, _from: any, next: any) => {
//   req_lang(lang_url, (lang: any) => { lng: lang })
// //   req_lang(lang_url, () => next())
// }

const rooturl = window.ROOT_LOCATION || location.origin

const check_auth = async(to: any, _from: any, next: any) => {
  useState().bcPath.value = ''
  const auth = localStorage.getItem('auth') || ''
  const check_url = `${window.ROOT_LOCATION || location.origin}/checkin`
  const login_url = `${location.origin}/ui/login`
  const mapkey = to.meta.uimapkey || 'ui'
  if (auth !== '') {
    const defs = store.state.app_defs.main.get(mapkey)
    if (defs && defs.checkin && useState().checkin.value) {
      next()
    }
    else {
      useState().checkin.value = true
      const res = await verify_auth(mapkey, check_url, login_url)
      // if (useState().connection.value.state === '')
      // TODO redirect to a connection error page or consider PWA offline mode
      if (res && res.defs)
        next()
      else next('/login')
    }
  }
  else { next('/login') }
}

const get_defs = async(mapkey: string) => {
  const auth = localStorage.getItem('auth') || ''
  const url = `${window.ROOT_LOCATION || location.origin}/checkin`
  if (auth !== '') {
    const res = await check_credentials(url, { data: auth, mapkey })
    if (res.token === auth)
      return res.defs || {}
    else
      return {}
  }
  else {
    return {}
  }
}

const routes: RouteRecordRaw[] = [
/*
  {
    path: '/home',
    alias: '/',
    name: 'Home',
    component: Home,
    meta: { layout: 'empty' },
  },
  {
    path: '/ui/samba',
    name: 'Samba',
    component: SambaModel,
    meta: { layout: 'AppLayout' },
  },
 */
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      requireAuth: true,
      layout: 'AppLayout',
      mapkey: 'kloud',
      uiMapkey: 'ui',
      rooturl,
    },
  //  beforeEnter: check_auth,
    // (_to: any, _from: any, next: any) => {
    //   req_lang(lang_url, () => next())
    // },
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { layout: 'empty', rooturl, use_logo: true, allow_register: false, allow_reset: false },
  },
  {
    path: '/logout',
    name: 'Logout',
    component: Logout,
    meta: { layout: 'empty', rooturl, use_logo: true },
  },
  // {
  //   path: '/auth/register',
  //   name: 'Register',
  //   component: Register,
  //   meta: { layout: 'GuestLayout' },
  // },
	/*
  {
    path: '/datalist',
    name: 'DataGrid',
    component: DataGrid,
    meta: {
      requireAuth: true,
      layout: 'AppLayout',
      uiMapkey: 'ui',
      mapkey: 'kloud',
      rooturl,
      bcpath: '#fa-book/librecloud/klouds',
    },
    beforeEnter: check_auth,
    // props: { lang: 'es' }, // get_lang,
    // beforeEnter: get_lang,
    // (_to: any, _from: any, next: any) => {
    //   req_lang(lang_url, () => next())
    // },
  },
	*/
  {
    path: '/:catchAll(.*)',
    name: '404',
    meta: { layout: 'Page404' },
    component: () => import('./views/404.vue'),
  },
  ...layoutsRoutes,
]

// const routes: RouteRecordRaw[] = pgRoutes
const router: any = createRouter({
  history: createWebHistory(),
  routes,
})
//  routes,
export default router
