import { createRouter, createWebHistory } from 'vue-router';
import { useAuthStore } from '../stores/auth';

import MapView from '../components/Manager/MapView.vue';

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue'),
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Auth/Login.vue'),
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Auth/Register.vue'),
  },
  {
    path: '/products',
    name: 'Products',
    component: () => import('../components/SuperAdmin/ProductManagement/ProductManagement.vue'),
  },
  {
    path: '/restaurants',
    name: 'Restaurants',
    component: () => import('../views/Restaurants/Index.vue'),
  },
  {
    path: '/restaurants/:id',
    name: 'RestaurantDetail',
    component: () => import('../views/Restaurants/Show.vue'),
  },
  {
    path: '/restaurants/:id/menu',
    name: 'RestaurantMenu',
    component: () => import('../views/Restaurants/Menu.vue'),
  },
  {
    path: '/cart',
    name: 'Cart',
    component: () => import('../views/Cart.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/checkout',
    name: 'Checkout',
    component: () => import('../views/Checkout.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/orders',
    name: 'Orders',
    component: () => import('../views/Orders/Index.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/orders/:id',
    name: 'OrderDetail',
    component: () => import('../views/Orders/Show.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('../views/Profile.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/customer/dashboard',
    name: 'CustomerDashboard',
    component: () => import('../views/Customer/Dashboard.vue'),
    meta: { requiresAuth: true, roles: ['customer'] },
  },
  {
    path: '/super-admin',
    component: () => import('../components/SuperAdmin/Layout.vue'),
    meta: { requiresAuth: true, roles: ['super-admin'] },
    children: [
      {
        path: '',
        name: 'SuperAdminDashboard',
        component: () => import('../components/SuperAdmin/ComprehensiveDashboard.vue'),
      },
      {
        path: 'restaurants',
        name: 'SuperAdminRestaurants',
        component: () => import('../components/SuperAdmin/RestaurantManagementTable.vue'),
      },
      {
        path: 'delivery-boys',
        name: 'SuperAdminDeliveryBoys',
        component: () => import('../components/Admin/DeliveryBoys.vue'),
      },
      {
        path: 'delivery-boy-earnings',
        name: 'SuperAdminDeliveryBoyEarnings',
        component: () => import('../components/SuperAdmin/DeliveryBoyEarnings.vue'),
      },
      {
        path: 'orders',
        name: 'SuperAdminOrders',
        component: () => import('../components/SuperAdmin/OrderManagement.vue'),
      },
      {
        path: 'earnings',
        name: 'SuperAdminEarnings',
        component: () => import('../components/SuperAdmin/EarningsManagement.vue'),
      },
      {
        path: 'users',
        name: 'SuperAdminUsers',
        component: () => import('../components/SuperAdmin/UserManagement/UserManagement.vue'),
      },
      {
        path: 'products',
        name: 'SuperAdminProducts',
        component: () => import('../components/SuperAdmin/ProductManagement/ProductManagement.vue'),
      },
      {
        path: 'categories',
        name: 'SuperAdminCategories',
        component: () => import('../components/SuperAdmin/CategoryManagement.vue'),
      },
      {
        path: 'promotions',
        name: 'SuperAdminPromotions',
        component: () => import('../views/SuperAdmin/RestaurantPromotions.vue'),
      },
      {
        path: 'profile',
        name: 'SuperAdminProfile',
        component: () => import('../components/SuperAdmin/Profile.vue'),
      },
      {
        path: 'settings',
        name: 'SuperAdminSettings',
        component: () => import('../components/SuperAdmin/SystemSettings.vue'),
      },
    ]
  },
  {
    path: '/admin',
    component: () => import('../layouts/AdminLayout.vue'),
    meta: { requiresAuth: true, roles: ['admin', 'super-admin'] },
    children: [
      {
        path: 'dashboard',
        name: 'AdminDashboard',
        component: () => import('../views/Admin/Dashboard.vue'),
      },
      {
        path: 'products',
        name: 'AdminProducts',
        component: () => import('../views/Admin/ProductManagement.vue'),
      },
      {
        path: 'users',
        name: 'AdminUsers',
        component: () => import('../views/Admin/Users.vue'),
      },
      {
        path: 'categories',
        name: 'AdminCategories',
        component: () => import('../views/Admin/Categories.vue'),
      },
      {
        path: 'orders',
        name: 'AdminOrders',
        component: () => import('../views/Admin/Orders.vue'),
      },
      {
        path: 'payments',
        name: 'AdminPayments',
        component: () => import('../views/Admin/Payments.vue'),
      },
      {
        path: 'settings',
        name: 'AdminSettings',
        component: () => import('../views/Admin/Settings.vue'),
      },
    ],
  },
  {
    path: '/manager',
    component: () => import('../components/Manager/Layout.vue'),
    meta: { requiresAuth: true, roles: ['manager'] },
    children: [
      {
        path: '',
        name: 'ManagerDashboard',
        component: () => import('../components/Manager/EnhancedDashboard.vue'),
      },
      {
        path: 'dashboard',
        name: 'ManagerDashboardAlt',
        component: () => import('../components/Manager/Dashboard.vue'),
      },
      {
        path: 'order-history',
        name: 'ManagerOrderHistory',
        component: () => import('../components/Manager/OrderHistory.vue'),
      },
      {
        path: 'cancelled-orders',
        name: 'ManagerCancelledOrders',
        component: () => import('../components/Manager/CancelledOrders.vue'),
      },
      {
        path: 'delivery-boys',
        name: 'ManagerDeliveryBoys',
        component: () => import('../components/Manager/DeliveryBoys.vue'),
      },
      {
        path: 'map',
        name: 'ManagerMapView',
        component: MapView,
      },
      {
        path: 'products',
        name: 'ManagerProducts',
        component: () => import('../components/Manager/Products.vue'),
      },
      {
        path: 'categories',
        name: 'ManagerCategories',
        component: () => import('../views/Manager/Categories.vue'),
      },
      {
        path: 'addons',
        name: 'ManagerAddons',
        component: () => import('../components/Manager/Addons.vue'),
      },
      {
        path: 'reviews',
        name: 'ManagerReviews',
        component: () => import('../components/Manager/Reviews.vue'),
      },
      {
        path: 'reports',
        name: 'ManagerReports',
        component: () => import('../components/Manager/Reports.vue'),
      },
      {
        path: 'profile',
        name: 'ManagerProfile',
        component: () => import('../components/Manager/Profile.vue'),
      },
      {
        path: 'settings',
        name: 'ManagerSettings',
        component: () => import('../components/Manager/Settings.vue'),
      },
    ]
  },
  {
    path: '/delivery/dashboard',
    name: 'DeliveryDashboard',
    component: () => import('../views/Delivery/Dashboard.vue'),
    meta: { requiresAuth: true, roles: ['delivery-boy', 'delivery_boy'] },
  },
  {
    path: '/delivery-boy',
    name: 'DeliveryBoyMobile',
    component: () => import('../views/DeliveryBoy/MobileApp.vue'),
    meta: { requiresAuth: true, roles: ['delivery-boy', 'delivery_boy'] },
  },
  {
    path: '/delivery-boy/notifications',
    name: 'DeliveryBoyNotifications',
    component: () => import('../views/DeliveryBoy/Notifications.vue'),
    meta: { requiresAuth: true, roles: ['delivery-boy', 'delivery_boy'] },
  },
  {
    path: '/delivery-boy/profile',
    name: 'DeliveryBoyProfile',
    component: () => import('../views/DeliveryBoy/Profile.vue'),
    meta: { requiresAuth: true, roles: ['delivery-boy', 'delivery_boy'] },
  },
  {
    path: '/delivery-boy/earnings',
    name: 'DeliveryBoyEarnings',
    component: () => import('../views/DeliveryBoy/Earnings.vue'),
    meta: { requiresAuth: true, roles: ['delivery-boy', 'delivery_boy'] },
  },
  {
    path: '/orders/:id/track',
    name: 'OrderTracking',
    component: () => import('../views/OrderTracking.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/wallet',
    name: 'Wallet',
    component: () => import('../views/Wallet.vue'),
    meta: { requiresAuth: true },
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore();
  
  // Check auth if token exists but user not loaded
  if (authStore.token && !authStore.user) {
    await authStore.checkAuth();
  }
  
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    next('/login');
  } else if ((to.path === '/login' || to.path === '/register') && authStore.isAuthenticated) {
    const role = authStore.userRole;
    if (role === 'super-admin') {
      next('/super-admin');
    } else if (role === 'admin') {
      next('/admin/dashboard');
    } else if (role === 'manager') {
      next('/manager');
    } else if (role === 'delivery-boy' || role === 'delivery_boy') {
      next('/delivery-boy');
    } else if (role === 'customer') {
      next('/customer/dashboard');
    } else {
      next('/');
    }
  } else if (to.meta.role && authStore.userRole !== to.meta.role) {
    next('/');
  } else if (to.meta.roles && !to.meta.roles.includes(authStore.userRole)) {
    next('/');
  } else {
    next();
  }
});

export default router;
