import { createRouter, createWebHistory } from 'vue-router';

import store from '../store';
import { TIBU_AREA_CODES } from '@/constants/tibuAreas';
import {
  CONFIG_EMPRESA_PERMISSIONS,
  CATALOG_AUX_PERMISSIONS,
  CATALOG_CLIENTES_PERMISSIONS,
} from '@/constants/routePermissions';

const routes = [
  { 
    path: '/', 
    name: 'Home', 
    component: () => import('../views/index.vue'),
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('../views/lavanderia/dashboard.vue'),
    // Recepcionista/Operador tienen lavanderia.dashboard; no dashboard.ver (mismo componente).
    meta: { permission: ['dashboard.ver', 'lavanderia.dashboard'] },
  },

  {
    path: "/auth/login",
    component: () => import("@/layouts/auth-layout.vue"),
    children: [
      {
        path: "",
        name: "login-route",
        component: () => import("@/views/auth/login.vue"),
        meta: { layout: 'auth' },
      },
      {
        path: '/auth/pass-recovery-boxed',
        name: 'pass-recovery-boxed',
        component: () => import('@/views/auth/pass_recovery_boxed.vue'),
        meta: { layout: 'auth' },
      },
{
    path: '/auth/changepw/:uuid',
        name: 'router-changepw-externo',
        component: () => import('@/views/users/changepw.vue'),
        meta: { layout: 'auth' },
      },
    ],
  },
  // Seguimiento de orden (público, sin auth - para QR). URL: /seguimiento/{folio_unico}
  {
    path: '/seguimiento/:folio_unico?',
    name: 'seguimiento-route',
    component: () => import('@/views/public/seguimiento.vue'),
    meta: { layout: 'auth', public: true },
  },
  // Usuarios
  {
    path: '/users/profile',
    name: 'users-profile-router',
    component: () => import('@/views/users/profile.vue'),
  },
  {
    path: '/users/lista',
    name: 'users-lista-router',
    component: () => import('@/views/users/index.vue'),
    meta: { permission: 'administracion.usuarios' },
  },
  // Módulo de Lavandería
  {
    path: '/lavanderia/dashboard',
    name: 'lavanderia-dashboard-router',
    component: () => import('@/views/lavanderia/dashboard.vue'),
    meta: { permission: ['dashboard.ver', 'lavanderia.dashboard'] },
  },
  {
    path: '/lavanderia/recepcion',
    name: 'lavanderia-recepcion-router',
    redirect: { name: 'ventas-pos-router' },
  },
  // Ventas (POS)
  {
    path: '/ventas/pos',
    name: 'ventas-pos-router',
    component: () => import('@/views/ventas/pos.vue'),
    meta: { permission: 'pos.vender' },
  },
  {
    path: '/ventas/caja',
    name: 'ventas-caja-router',
    component: () => import('@/views/ventas/caja.vue'),
    meta: { permission: 'caja.administrar' },
  },
  {
    path: '/ventas/tickets',
    name: 'ventas-tickets-router',
    component: () => import('@/views/ventas/tickets.vue'),
    meta: { permission: ['pos.vender', 'lavanderia.recepcion', 'lavanderia.consultar'] },
  },
  // Catálogos
  {
    path: '/catalogos/clientes',
    name: 'catalogos-clientes-router',
    component: () => import('@/views/catalogos/clientes.vue'),
    meta: { permission: CATALOG_CLIENTES_PERMISSIONS },
  },
  {
    path: '/catalogos/cliente-categorias',
    name: 'catalogos-cliente-categorias-router',
    component: () => import('@/views/catalogos/cliente-categorias.vue'),
    meta: { permission: CATALOG_CLIENTES_PERMISSIONS },
  },
  {
    path: '/catalogos/etapas',
    name: 'catalogos-etapas-router',
    component: () => import('@/views/catalogos/etapas.vue'),
    meta: { permission: CATALOG_AUX_PERMISSIONS },
  },
  {
    path: '/catalogos/tipos-servicio',
    name: 'catalogos-tipos-servicio-router',
    component: () => import('@/views/catalogos/tipos-servicio.vue'),
    meta: { permission: CATALOG_AUX_PERMISSIONS },
  },
  {
    path: '/catalogos/productos-legacy',
    name: 'catalogos-productos-legacy-router',
    component: () => import('@/views/catalogos/productos-legacy.vue'),
    meta: { permission: CATALOG_AUX_PERMISSIONS },
  },
  {
    path: '/catalogos/productos',
    redirect: { name: 'catalogos-productos-legacy-router' },
  },
  {
    path: '/inventario/movimientos-rapidos',
    name: 'inventory-quick-movements-router',
    component: () => import('@/views/inventory/quick-movements.vue'),
    meta: { permission: 'inventory.manage' },
  },
  {
    path: '/inventario/productos',
    name: 'inventory-products-router',
    component: () => import('@/views/inventory/products.vue'),
    meta: { permission: ['inventory.view', 'inventory.manage'] },
  },
  {
    path: '/inventario/documentos',
    name: 'inventory-transfer-documents-router',
    component: () => import('@/views/inventory/transfer-documents.vue'),
    meta: { permission: ['inventory.view', 'inventory.manage'] },
  },
  {
    path: '/inventario/documentos/crear',
    name: 'inventory-transfer-document-create-router',
    component: () => import('@/views/inventory/transfer-document-detail.vue'),
    meta: { permission: 'inventory.manage' },
  },
  {
    path: '/inventario/documentos/:id',
    name: 'inventory-transfer-document-detail-router',
    component: () => import('@/views/inventory/transfer-document-detail.vue'),
    meta: { permission: ['inventory.view', 'inventory.manage'] },
  },
  // Reportes
  {
    path: '/reportes/cierre-dia',
    name: 'reportes-cierre-dia-router',
    component: () => import('@/views/reportes/cierre-dia.vue'),
    meta: { permission: 'reportes.ver' },
  },
  {
    path: '/reportes/ventas-producto',
    name: 'reportes-ventas-producto-router',
    component: () => import('@/views/reportes/ventas-producto.vue'),
    meta: { permission: 'reportes.ver' },
  },
  {
    path: '/lavanderia/operador/entrada',
    name: 'lavanderia-operador-entry-router',
    component: () => import('@/views/lavanderia/operador-entry.vue'),
    meta: { permission: 'lavanderia.operador' },
  },
  {
    path: '/lavanderia/operador/:area?',
    name: 'lavanderia-operador-router',
    component: () => import('@/views/lavanderia/operador.vue'),
    meta: { permission: 'lavanderia.operador' },
  },
  {
    path: '/lavanderia/escanear',
    name: 'lavanderia-escanear-router',
    component: () => import('@/views/lavanderia/escanear-unificado.vue'),
    meta: { permission: 'lavanderia.operador' },
  },
  {
    path: '/lavanderia/area/:areaCode',
    name: 'lavanderia-area-router',
    component: () => import('@/views/lavanderia/area.vue'),
    meta: { requireAreaOperate: true },
  },
  {
    path: '/lavanderia/lista',
    name: 'lavanderia-lista-router',
    component: () => import('@/views/lavanderia/lista.vue'),
    meta: { permission: ['lavanderia.consultar', 'lavanderia.recepcion'] },
  },
  // Reportes - Ventas al mes
  {
    path: '/ventas/mensual',
    name: 'ventas-mensual-router',
    component: () => import('@/views/ventas/mensuales.vue'),
    meta: { permission: ['dashboard.ver', 'reportes.ver'] },
  },
  // Módulo de Administración - Roles y Permisos
  {
    path: '/roles/lista',
    name: 'roles-lista-router',
    component: () => import('@/views/roles/index.vue'),
    meta: { permission: 'administracion.roles' },
  },
  {
    path: '/admin/configuracion-empresa',
    name: 'admin-config-empresa-router',
    component: () => import('@/views/admin/configuracion-empresa.vue'),
    meta: { permission: CONFIG_EMPRESA_PERMISSIONS },
  },
  {
    path: '/admin/areas',
    name: 'admin-areas-router',
    component: () => import('@/views/admin/areas.vue'),
    meta: { permission: 'administracion.areas' },
  },
  {
    path: '/admin/impresoras',
    name: 'admin-impresoras-router',
    component: () => import('@/views/admin/impresoras.vue'),
    meta: { permission: 'administracion.areas' },
  },
  {
    path: '/admin/garment-types',
    name: 'admin-garment-types-router',
    component: () => import('@/views/admin/garment-types.vue'),
    meta: { permission: 'administracion.areas' },
  },
  {
    path: '/admin/catalogo-categorias',
    name: 'admin-catalogo-categorias-router',
    component: () => import('@/views/admin/laundry-pos-catalog.vue'),
    meta: { permission: 'administracion.areas', catalogMode: 'categories' },
  },
  {
    path: '/admin/catalogo-productos',
    name: 'admin-catalogo-productos-router',
    component: () => import('@/views/admin/laundry-pos-catalog.vue'),
    meta: { permission: 'administracion.areas', catalogMode: 'products', lockedTipo: 'producto' },
  },
  {
    path: '/admin/catalogo-servicios',
    name: 'admin-catalogo-servicios-router',
    component: () => import('@/views/admin/laundry-pos-catalog.vue'),
    meta: { permission: 'administracion.areas', catalogMode: 'products', lockedTipo: 'servicio' },
  },
  {
    path: '/admin/laundry-pos-catalog',
    redirect: (to) => {
      const tab = typeof to.query.tab === 'string' ? to.query.tab : '';
      if (tab === 'categories') {
        return { name: 'admin-catalogo-categorias-router' };
      }
      if (to.query.tipo === 'producto') {
        return { name: 'admin-catalogo-productos-router' };
      }
      return { name: 'admin-catalogo-servicios-router' };
    },
  },
];

const router = new createRouter({
  // mode: 'history',
  history: createWebHistory(),
  linkExactActiveClass: 'active',
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { left: 0, top: 0 };
    }
  },
});

router.beforeEach(async (to, from, next) => {
  const token = window.localStorage.getItem("token");
  
  if (to.meta && to.meta.layout && to.meta.layout == 'auth') {
    store.commit('setLayout', 'auth');
  } else {
    store.commit('setLayout', 'app');
  }

  if (to.meta && to.meta.public) {
    store.commit('setLayout', 'auth');
    next();
    return;
  }
  if (to.name !== 'login-route' && to.name !== 'registro-route' && !token) {
    next('/auth/login')
    return;
  } else if (token && to.name == 'login-route') {
    store.commit('setLayout', 'app');
    next("/");
    return;
  }

  // Verificar permisos si la ruta requiere uno
  if (to.meta && to.meta.permission && token) {
    try {
      const { usePermissions } = await import('@/composables/use-permissions');
      const { loadPermissions, hasPermission, hasAnyPermission } = usePermissions();
      
      await loadPermissions();
      
      const requiredPermission = to.meta.permission;
      let hasAccess = false;
      
      if (Array.isArray(requiredPermission)) {
        hasAccess = hasAnyPermission(requiredPermission);
      } else {
        hasAccess = hasPermission(requiredPermission);
      }
      
      if (!hasAccess) {
        try {
          sessionStorage.setItem('route_access_denied', to.fullPath);
        } catch {
          /* ignore */
        }
        if (hasAnyPermission(['dashboard.ver', 'lavanderia.dashboard'])) {
          next({ name: 'lavanderia-dashboard-router', replace: true });
        } else if (hasPermission('pos.vender')) {
          next({ name: 'ventas-pos-router', replace: true });
        } else {
          next({ name: 'Home', replace: true });
        }
        return;
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error('Error checking permissions:', error);
      }
      // En caso de error, permitir acceso (fallback)
    }
  }

  if (to.meta && to.meta.requireAreaOperate && token) {
    try {
      const { usePermissions } = await import('@/composables/use-permissions');
      const { loadPermissions, hasPermission } = usePermissions();
      await loadPermissions();
      const code = to.params.areaCode;
      if (!code || typeof code !== 'string') {
        next({ name: 'Home', replace: true });
        return;
      }
      const perm = `area.${code}.operate`;
      if (!hasPermission(perm)) {
        next({ name: 'Home', replace: true });
        return;
      }
    } catch (e) {
      if (import.meta.env.DEV) {
        console.error(e);
      }
      next({ name: 'Home', replace: true });
      return;
    }
  }
  
  // Entrada principal por rol/permisos para evitar pantallas "vacías" en Home.
  if (to.name === 'Home' && token) {
    try {
      const { usePermissions } = await import('@/composables/use-permissions');
      const { loadPermissions, hasPermission, hasAnyPermission } = usePermissions();
      
      await loadPermissions();

      if (hasPermission('dashboard.ver') || hasPermission('lavanderia.dashboard')) {
        next({ name: 'lavanderia-dashboard-router', replace: true });
        return;
      }

      if (hasPermission('pos.vender')) {
        next({ name: 'ventas-pos-router', replace: true });
        return;
      }

      if (hasPermission('caja.administrar')) {
        next({ name: 'ventas-caja-router', replace: true });
        return;
      }

      if (hasAnyPermission(['inventory.view', 'inventory.manage'])) {
        next({ name: 'inventory-products-router', replace: true });
        return;
      }

      const firstAreaCode = TIBU_AREA_CODES.find((code) => hasPermission(`area.${code}.operate`));
      if (firstAreaCode) {
        next({ name: 'lavanderia-area-router', params: { areaCode: firstAreaCode }, replace: true });
        return;
      }

      if (hasPermission('lavanderia.operador')) {
        next({ name: 'lavanderia-operador-entry-router', replace: true });
        return;
      }

      if (hasAnyPermission(['lavanderia.consultar', 'lavanderia.recepcion'])) {
        next({ name: 'lavanderia-lista-router', replace: true });
        return;
      }

      next({ name: 'users-profile-router', replace: true });
      return;
    } catch (error) {
      console.error('Error checking dashboard permission:', error);
    }
  }
  
  next();
});

export default router;
