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

const router = createRouter({
  history: import.meta.env.VITE_ROUTER_MODE === 'hash'
    ? createWebHashHistory()
    : createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: { public: true },
    },
    {
      path: '/sso/callback',
      name: 'sso-callback',
      component: () => import('../views/SsoCallbackView.vue'),
      meta: { public: true },
    },
    {
      path: '/sso/bind',
      name: 'sso-bind',
      component: () => import('../views/SsoBindView.vue'),
      meta: { public: true },
    },
    {
      path: '/timetable',
      name: 'public-timetable',
      component: () => import('../views/TimetableView.vue'),
      meta: { public: true },
    },
    {
      path: '/venue-display/:type(classroom|building)/:id',
      name: 'venue-display',
      component: () => import('../views/VenueDisplayView.vue'),
      meta: { public: true },
    },
    {
      path: '/activate',
      name: 'activate-account',
      component: () => import('../views/AccountActivationView.vue'),
      meta: { public: true },
    },
    {
      path: '/verify/:verificationCode?',
      name: 'official-document-verification',
      component: () => import('../views/OfficialDocumentVerifyView.vue'),
      meta: { public: true },
    },
    {
      path: '/',
      component: AdminLayout,
      children: [
        { path: '', redirect: '/dashboard' },
        {
          path: 'dashboard',
          name: 'dashboard',
          component: () => import('../views/DashboardView.vue'),
        },
        {
          path: 'account',
          name: 'account',
          component: () => import('../views/AccountView.vue'),
        },
        {
          path: 'my-profile',
          name: 'my-profile',
          component: () => import('../views/StudentProfileView.vue'),
          meta: { roles: ['Student'] },
        },
        {
          path: 'base-data',
          redirect: '/base-data/organization',
        },
        {
          path: 'base-data/organization',
          name: 'organization-data',
          component: () => import('../views/BaseDataView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin'],
            baseGroup: 'organization',
          },
        },
        {
          path: 'base-data/terms',
          name: 'term-data',
          component: () => import('../views/BaseDataView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin'],
            baseGroup: 'terms',
          },
        },
        {
          path: 'base-data/facilities',
          name: 'facility-data',
          component: () => import('../views/BaseDataView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin'],
            baseGroup: 'facilities',
          },
        },
        {
          path: 'base-data/course-categories',
          name: 'course-category-data',
          component: () => import('../views/BaseDataView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin'],
            baseGroup: 'course-categories',
          },
        },
        {
          path: 'personnel',
          redirect: '/teachers',
        },
        {
          path: 'teachers',
          name: 'teachers',
          component: () => import('../views/PersonnelView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Counselor'],
            registry: 'teachers',
          },
        },
        {
          path: 'students',
          name: 'students',
          component: () => import('../views/PersonnelView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Counselor'],
            registry: 'students',
          },
        },
        {
          path: 'courses',
          name: 'courses',
          component: () => import('../views/CoursesView.vue'),
        },
        {
          path: 'curriculum',
          name: 'curriculum',
          component: () => import('../views/CurriculumView.vue'),
          meta: { roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin'] },
        },
        {
          path: 'my-curriculum',
          name: 'my-curriculum',
          component: () => import('../views/StudentCurriculumView.vue'),
          meta: { roles: ['Student'] },
        },
        {
          path: 'academic-planning',
          name: 'academic-planning',
          component: () => import('../views/AcademicPlanningView.vue'),
          meta: { roles: ['Student'] },
        },
        {
          path: 'teaching-tasks',
          name: 'teaching-tasks',
          component: () => import('../views/TeachingTasksView.vue'),
          meta: { roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin'] },
        },
        {
          path: 'teaching-preferences',
          name: 'teaching-preferences',
          component: () => import('../views/TeachingPreferencesView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Teacher'],
          },
        },
        {
          path: 'schedules',
          name: 'schedules',
          component: () => import('../views/SchedulesView.vue'),
          meta: { roles: ['SuperAdmin', 'AcademicAdmin'] },
        },
        {
          path: 'class-timetable',
          name: 'class-timetable',
          component: () => import('../views/TimetableView.vue'),
        },
        {
          path: 'my-timetable',
          name: 'my-timetable',
          component: () => import('../views/TimetableView.vue'),
          meta: { roles: ['Student', 'Teacher'], mine: true },
        },
        {
          path: 'teacher-timetable/:teacherId',
          name: 'teacher-timetable',
          component: () => import('../views/TimetableView.vue'),
          meta: { teacherView: true },
        },
        {
          path: 'teacher-roster',
          name: 'teacher-roster',
          component: () => import('../views/TeacherRosterView.vue'),
          meta: { roles: ['Teacher'] },
        },
        {
          path: 'teacher-attendance',
          name: 'teacher-attendance',
          component: () => import('../views/TeacherAttendanceView.vue'),
          meta: { roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Teacher', 'Counselor'] },
        },
        {
          path: 'my-attendance',
          name: 'my-attendance',
          component: () => import('../views/StudentAttendanceView.vue'),
          meta: { roles: ['Student'] },
        },
        {
          path: 'free-classrooms',
          name: 'free-classrooms',
          component: () => import('../views/FreeClassroomsView.vue'),
          meta: { roles: ['Student'] },
        },
        {
          path: 'venue-displays',
          name: 'venue-displays',
          component: () => import('../views/VenueDisplaysView.vue'),
          meta: { roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin'] },
        },
        {
          path: 'classroom-reservations',
          name: 'classroom-reservations',
          component: () => import('../views/ClassroomReservationsView.vue'),
        },
        {
          path: 'experiments',
          name: 'experiments',
          component: () => import('../views/ExperimentsView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Teacher', 'Student'],
          },
        },
        {
          path: 'experiment-grades',
          name: 'experiment-grades',
          component: () => import('../views/ExperimentGradesView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Teacher', 'Student'],
          },
        },
        {
          path: 'course-selections',
          name: 'course-selections',
          component: () => import('../views/CourseSelectionView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Student'],
          },
        },
        {
          path: 'grades',
          name: 'grades',
          component: () => import('../views/GradesView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Teacher', 'Student', 'Counselor'],
          },
        },
        {
          path: 'grades/:sheetId/statistics',
          name: 'course-grade-statistics',
          component: () => import('../views/CourseGradeStatisticsView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Leader', 'Counselor', 'Student'],
          },
        },
        {
          path: 'grade-analytics',
          name: 'grade-analytics',
          component: () => import('../views/GradeAnalyticsView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Leader', 'Teacher'],
          },
        },
        {
          path: 'event-analytics',
          name: 'event-analytics',
          component: () => import('../views/EventAnalyticsView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Leader'],
          },
        },
        {
          path: 'other-exams',
          name: 'other-exams',
          component: () => import('../views/OtherExamsView.vue'),
          meta: { roles: ['SuperAdmin', 'AcademicAdmin', 'Student'] },
        },
        {
          path: 'exams',
          name: 'exams',
          component: () => import('../views/ExamsView.vue'),
          meta: { roles: ['SuperAdmin', 'AcademicAdmin', 'Teacher', 'Student'] },
        },
        {
          path: 'makeup-exams',
          name: 'makeup-exams',
          component: () => import('../views/MakeupExamsView.vue'),
          meta: { roles: ['SuperAdmin', 'AcademicAdmin', 'Teacher', 'Student'] },
        },
        {
          path: 'course-adjustments',
          name: 'course-adjustments',
          component: () => import('../views/CourseAdjustmentsView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Teacher'],
          },
        },
        {
          path: 'notifications',
          name: 'notifications',
          component: () => import('../views/NotificationCenterView.vue'),
        },
        {
          path: 'approvals',
          name: 'approvals',
          component: () => import('../views/ApprovalCenterView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Counselor', 'Teacher', 'Student'],
          },
        },
        {
          path: 'warnings',
          name: 'warnings',
          component: () => import('../views/WarningsView.vue'),
          meta: { roles: ['SuperAdmin', 'AcademicAdmin', 'Counselor', 'Student'] },
        },
        {
          path: 'student-status-changes',
          name: 'student-status-changes',
          component: () => import('../views/StudentStatusChangesView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Counselor', 'Student'],
          },
        },
        {
          path: 'official-documents',
          name: 'official-documents',
          component: () => import('../views/OfficialDocumentsView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Student'],
          },
        },
        {
          path: 'graduation-audits',
          name: 'graduation-audits',
          component: () => import('../views/GraduationAuditsView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Student'],
          },
        },
        {
          path: 'degree-awards',
          name: 'degree-awards',
          component: () => import('../views/DegreeAwardsView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Student'],
          },
        },
        {
          path: 'graduation-clearance',
          name: 'graduation-clearance',
          component: () => import('../views/GraduationClearanceView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Counselor', 'Student'],
          },
        },
        {
          path: 'users',
          name: 'users',
          component: () => import('../views/UsersView.vue'),
          meta: { roles: ['SuperAdmin'] },
        },
        {
          path: 'operations',
          name: 'operations',
          component: () => import('../views/OperationsConsoleView.vue'),
          meta: { roles: ['SuperAdmin'] },
        },
        {
          path: 'evaluations',
          name: 'evaluations',
          component: () => import('../views/EvaluationView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Teacher', 'Student', 'Leader'],
          },
        },
        {
          path: 'statistics',
          name: 'statistics',
          component: () => import('../views/StatisticsView.vue'),
          meta: {
            roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Leader'],
          },
        },
      ],
    },
    { path: '/:pathMatch(.*)*', redirect: '/dashboard' },
  ],
})

router.beforeEach((to) => {
  const auth = useAuthStore()
  if (!to.meta.public && !auth.isLoggedIn) {
    return { name: 'login', query: { redirect: to.fullPath } }
  }
  if (to.name === 'login' && auth.isLoggedIn) return { name: 'dashboard' }
  const roles = to.meta.roles as string[] | undefined
  if (roles && !roles.some((role) => auth.user?.roles.includes(role))) {
    return { name: 'dashboard' }
  }
})

export default router
