import type { RouteRecordRaw } from 'vue-router'
import { preloadCache } from '@/utils/cache'

// Lazy loading with preloading hints
const DashboardPage = () => import('../pages/DashboardPage.vue')
const ListsPage = () => import('../pages/ListsPage.vue')
const ListDetailPage = () => import('../pages/ListDetailPage.vue')
const GroupsPage = () => import('../pages/GroupsPage.vue')
const GroupDetailPage = () => import('../pages/GroupDetailPage.vue')
const HouseholdSettings = () => import('../pages/HouseholdSettings.vue')
const AccountPage = () => import('../pages/AccountPage.vue')
const ChoresPage = () => import('../pages/ChoresPage.vue')
const ExpensesPage = () => import('../pages/ExpensesPage.vue')
const ExpensePage = () => import('../pages/ExpensePage.vue')

// Auth pages with aggressive preloading
const LoginPage = () => import('../pages/LoginPage.vue')
const SignupPage = () => import('../pages/SignupPage.vue')
const AuthCallbackPage = () => import('../pages/AuthCallbackPage.vue')

// Error pages
const ErrorNotFound = () => import('../pages/ErrorNotFound.vue')

// Layout components with preloading
const MainLayout = () => import('../layouts/MainLayout.vue')
const AuthLayout = () => import('../layouts/AuthLayout.vue')

// Loading components for better UX
const DashboardSkeleton = () => import('../components/ui/SkeletonDashboard.vue')
const ListSkeleton = () => import('../components/ui/SkeletonList.vue')

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: MainLayout,
    children: [
      { path: '', redirect: '/dashboard' },
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: DashboardPage,
        meta: {
          keepAlive: true,
          preload: true, // Critical route - preload immediately
          skeleton: DashboardSkeleton,
          title: 'Dashboard'
        },
      },
      {
        path: 'lists',
        name: 'PersonalLists',
        component: ListsPage,
        meta: {
          keepAlive: true,
          preload: false,
          skeleton: ListSkeleton,
          title: 'My Lists'
        },
      },
      {
        path: 'lists/:id',
        name: 'ListDetail',
        component: ListDetailPage,
        props: true,
        meta: {
          keepAlive: true,
          preload: false,
          skeleton: ListSkeleton,
          title: 'List Details'
        },
        // Preload data when route is entered
        beforeEnter: async (to) => {
          const listId = String(to.params.id);

          // Preload list data
          await Promise.allSettled([
            preloadCache(`list-${listId}`, async () => {
              const { apiClient, API_ENDPOINTS } = await import('@/services/api');
              return apiClient.get(API_ENDPOINTS.LISTS.BY_ID(listId));
            }),
            preloadCache(`list-items-${listId}`, async () => {
              const { apiClient, API_ENDPOINTS } = await import('@/services/api');
              return apiClient.get(API_ENDPOINTS.LISTS.ITEMS(listId));
            })
          ]);
        }
      },
      {
        path: 'groups',
        name: 'GroupsList',
        component: GroupsPage,
        meta: {
          keepAlive: true,
          preload: false,
          skeleton: ListSkeleton,
          title: 'Groups'
        },
      },
      {
        path: 'groups/:id',
        name: 'GroupDetail',
        component: GroupDetailPage,
        props: true,
        meta: {
          keepAlive: true,
          preload: false,
          title: 'Group Details'
        },
      },
      {
        path: 'groups/:id/settings',
        name: 'GroupSettings',
        component: HouseholdSettings,
        props: true,
        meta: {
          keepAlive: false,
          requiresAuth: true,
          title: 'Group Settings'
        },
      },
      {
        path: 'groups/:groupId/lists',
        name: 'GroupLists',
        component: ListsPage,
        props: true,
        meta: {
          keepAlive: true,
          skeleton: ListSkeleton,
          title: 'Group Lists'
        },
      },
      {
        path: 'account',
        name: 'Account',
        component: AccountPage,
        meta: {
          keepAlive: true,
          requiresAuth: true,
          title: 'Account Settings'
        },
      },
      {
        path: '/groups/:groupId/chores',
        name: 'GroupChores',
        component: ChoresPage,
        props: (route) => ({ groupId: Number(route.params.groupId) }),
        meta: {
          requiresAuth: true,
          keepAlive: false,
          skeleton: ListSkeleton,
          title: 'Chores'
        },
      },
      {
        path: '/groups/:groupId/expenses',
        name: 'GroupExpenses',
        component: ExpensesPage,
        props: (route) => ({ groupId: Number(route.params.groupId) }),
        meta: {
          requiresAuth: true,
          keepAlive: false,
          skeleton: ListSkeleton,
          title: 'Expenses'
        },
      },
      {
        path: '/chores',
        name: 'Chores',
        component: ChoresPage,
        meta: {
          requiresAuth: true,
          keepAlive: false,
          skeleton: ListSkeleton,
          title: 'My Chores'
        },
      },
      {
        path: '/expenses',
        name: 'Expenses',
        component: ExpensePage,
        meta: {
          requiresAuth: true,
          keepAlive: false,
          skeleton: ListSkeleton,
          title: 'My Expenses'
        },
      },
    ],
  },
  {
    path: '/auth',
    component: AuthLayout,
    children: [
      {
        path: 'login',
        name: 'Login',
        component: LoginPage,
        meta: {
          title: 'Sign In',
          public: true
        }
      },
      {
        path: 'signup',
        name: 'Signup',
        component: SignupPage,
        meta: {
          title: 'Sign Up',
          public: true
        }
      },
      {
        path: 'callback',
        name: 'AuthCallback',
        component: AuthCallbackPage,
        meta: {
          title: 'Signing In...',
          public: true
        }
      },
    ],
  },
  {
    path: '/:catchAll(.*)*',
    name: '404',
    component: ErrorNotFound,
    meta: {
      title: 'Page Not Found',
      public: true
    }
  },
]

// Route-based preloading for critical paths
export const preloadCriticalRoutes = async () => {
  // Preload dashboard components and data
  await Promise.allSettled([
    DashboardPage(),
    MainLayout(),

    // Preload commonly accessed routes
    ListsPage(),
    GroupsPage(),

    // Preload user data that's likely to be needed
    preloadCache('user-groups', async () => {
      const { groupService } = await import('@/services/groupService');
      return groupService.getUserGroups();
    }),

    preloadCache('user-profile', async () => {
      const { apiClient } = await import('@/services/api');
      return apiClient.get('/users/me');
    })
  ]);
};

// Smart preloading based on user interaction
export const preloadOnHover = (routeName: string) => {
  const route = routes.find(r => r.name === routeName ||
    r.children?.some(child => child.name === routeName));

  if (route) {
    // Preload the component
    if (typeof route.component === 'function') {
      (route.component as () => Promise<any>)();
    }

    // Check for child routes
    if (route.children) {
      const childRoute = route.children.find(child => child.name === routeName);
      if (childRoute && typeof childRoute.component === 'function') {
        (childRoute.component as () => Promise<any>)();
      }
    }
  }
};

// Chunk preloading for progressive enhancement
export const preloadChunks = {
  // Preload auth flow when user hovers login button
  auth: () => Promise.allSettled([
    LoginPage(),
    SignupPage(),
    AuthLayout()
  ]),

  // Preload list management when user navigates to lists
  lists: () => Promise.allSettled([
    ListsPage(),
    ListDetailPage()
  ]),

  // Preload group features
  groups: () => Promise.allSettled([
    GroupsPage(),
    GroupDetailPage(),
    HouseholdSettings()
  ]),

  // Preload chore management
  chores: () => Promise.allSettled([
    ChoresPage()
  ]),

  // Preload expense tracking
  expenses: () => Promise.allSettled([
    ExpensesPage(),
    ExpensePage()
  ])
};

export default routes
