import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { QueryClientProvider } from "@tanstack/react-query";
import { BrowserRouter, Routes, Route, Navigate, useNavigate } from "react-router-dom";
import { AuthProvider } from "@/contexts/AuthContext";
import ProtectedRoute from "@/components/ProtectedRoute";
import StudentLayout from "@/components/StudentLayout";
import TeacherLayout from "@/components/TeacherLayout";
import AdminLmsLayout from "@/components/AdminLmsLayout";
import Login from "@/pages/Login";
import Register from "@/pages/Register";
import EmailVerification from "@/pages/EmailVerification";
import OnboardingWizard from "@/pages/OnboardingWizard";
import ForgotPassword from "@/pages/ForgotPassword";
import ResetPassword from "@/pages/ResetPassword";
import ScoreVerification from "@/pages/ScoreVerification";
// Original platform pages
import AdminDashboard from "@/pages/AdminDashboard";
import UsersPage from "@/pages/UsersPage";
import EntitiesPage from "@/pages/EntitiesPage";
import AssignmentsPage from "@/pages/AssignmentsPage";
import ExamsListPage from "@/pages/ExamsListPage";
import ExamStructuresPage from "@/pages/ExamStructuresPage";
import RubricsPage from "@/pages/RubricsPage";
import GenerationPage from "@/pages/GenerationPage";
import ApprovalWorkflowsPage from "@/pages/ApprovalWorkflowsPage";
import ClassroomsPage from "@/pages/ClassroomsPage";
import StudentPerformancePage from "@/pages/StudentPerformancePage";
import StatsCorporatePage from "@/pages/StatsCorporatePage";
import RecordPage from "@/pages/RecordPage";
import VocabularyPage from "@/pages/VocabularyPage";
import GrammarPage from "@/pages/GrammarPage";
import PaymentRecordPage from "@/pages/PaymentRecordPage";
import TicketsPage from "@/pages/TicketsPage";
import SettingsPage from "@/pages/SettingsPage";
import ProfilePage from "@/pages/ProfilePage";
import ExamPage from "@/pages/ExamPage";
// Student pages
import StudentDashboard from "@/pages/student/StudentDashboard";
import StudentCourses from "@/pages/student/StudentCourses";
import StudentCourseDetail from "@/pages/student/StudentCourseDetail";
import StudentAssignments from "@/pages/student/StudentAssignments";
import StudentGrades from "@/pages/student/StudentGrades";
import StudentAttendance from "@/pages/student/StudentAttendance";
import StudentTimetable from "@/pages/student/StudentTimetable";
import StudentProfile from "@/pages/student/StudentProfile";
// Adaptive learning pages
import SubjectSelection from "@/pages/student/SubjectSelection";
import DiagnosticTest from "@/pages/student/DiagnosticTest";
import ProficiencyProfile from "@/pages/student/ProficiencyProfile";
import LearningPlanPage from "@/pages/student/LearningPlan";
import TopicLearning from "@/pages/student/TopicLearning";
// Teacher pages
import TeacherDashboard from "@/pages/teacher/TeacherDashboard";
import TeacherCourses from "@/pages/teacher/TeacherCourses";
import CourseBuilder from "@/pages/teacher/CourseBuilder";
import TeacherAssignments from "@/pages/teacher/TeacherAssignments";
import TeacherAssignmentDetail from "@/pages/teacher/TeacherAssignmentDetail";
import TeacherAttendance from "@/pages/teacher/TeacherAttendance";
import TeacherStudents from "@/pages/teacher/TeacherStudents";
import TeacherTimetable from "@/pages/teacher/TeacherTimetable";
import TeacherProfile from "@/pages/teacher/TeacherProfile";
import AdaptiveSettings from "@/pages/teacher/AdaptiveSettings";
// Admin LMS pages
import AdminLmsDashboard from "@/pages/admin/AdminLmsDashboard";
import AdminCourses from "@/pages/admin/AdminCourses";
import AdminStudents from "@/pages/admin/AdminStudents";
import AdminTeachers from "@/pages/admin/AdminTeachers";
import AdminBatches from "@/pages/admin/AdminBatches";
import AdminBatchDetail from "@/pages/admin/AdminBatchDetail";
import AdminTimetable from "@/pages/admin/AdminTimetable";
import AdminReports from "@/pages/admin/AdminReports";
import AdminSettings from "@/pages/admin/AdminSettings";
import AdminProfileLms from "@/pages/admin/AdminProfile";
import TaxonomyManager from "@/pages/admin/TaxonomyManager";
import ResourceManager from "@/pages/admin/ResourceManager";
import AcademicYearManager from "@/pages/admin/AcademicYearManager";
import DepartmentManager from "@/pages/admin/DepartmentManager";
import AdmissionList from "@/pages/admin/AdmissionList";
import AdmissionDetail from "@/pages/admin/AdmissionDetail";
import AdmissionRegisterPage from "@/pages/admin/AdmissionRegisterPage";
import InstitutionalExamSessions from "@/pages/admin/InstitutionalExamSessions";
import MarksheetManager from "@/pages/admin/MarksheetManager";
import AdminStudentLeave from "@/pages/admin/AdminStudentLeave";
import AdminFees from "@/pages/admin/AdminFees";
import AdminLessons from "@/pages/admin/AdminLessons";
import AdminGradebook from "@/pages/admin/AdminGradebook";
import AdminStudentProgress from "@/pages/admin/AdminStudentProgress";
import AdminLibrary from "@/pages/admin/AdminLibrary";
import AdminActivities from "@/pages/admin/AdminActivities";
import AdminFacilities from "@/pages/admin/AdminFacilities";
import AdmissionApplication from "@/pages/AdmissionApplication";
import SubjectRegistrationPage from "@/pages/student/SubjectRegistrationPage";
// Courseware pages
import CourseChapters from "@/pages/teacher/CourseChapters";
import ChapterDetail from "@/pages/teacher/ChapterDetail";
import AiWorkbench from "@/pages/teacher/AiWorkbench";
import TeacherDiscussionBoard from "@/pages/teacher/TeacherDiscussionBoard";
import TeacherAnnouncements from "@/pages/teacher/TeacherAnnouncements";
import StudentChapterView from "@/pages/student/StudentChapterView";
import StudentDiscussionBoard from "@/pages/student/StudentDiscussionBoard";
import StudentAnnouncements from "@/pages/student/StudentAnnouncements";
import StudentMessages from "@/pages/student/StudentMessages";
import StudentJourney from "@/pages/student/StudentJourney";
import AiEnglishCourse from "@/pages/student/AiEnglishCourse";
import AiIeltsCourse from "@/pages/student/AiIeltsCourse";
import ExamSession from "@/pages/student/ExamSession";
import ExamStatus from "@/pages/student/ExamStatus";
import ExamResults from "@/pages/student/ExamResults";
import GapAnalysis from "@/pages/student/GapAnalysis";
import CourseDelivery from "@/pages/student/CourseDelivery";
import GradingQueue from "@/pages/admin/GradingQueue";
import CourseConfig from "@/pages/admin/CourseConfig";
import ModuleBuilder from "@/pages/admin/ModuleBuilder";
import CourseProgress from "@/pages/teacher/CourseProgress";
import PlacementBriefing from "@/pages/student/PlacementBriefing";
import PlacementTest from "@/pages/student/PlacementTest";
import PlacementResults from "@/pages/student/PlacementResults";
import PlacementAccess from "@/pages/student/PlacementAccess";
import FaqManager from "@/pages/admin/FaqManager";
import NotificationRules from "@/pages/admin/NotificationRules";
import ApprovalWorkflowConfig from "@/pages/admin/ApprovalWorkflowConfig";
import RolesPermissions from "@/pages/admin/RolesPermissions";
import AuthorityMatrix from "@/pages/admin/AuthorityMatrix";
import UserRoles from "@/pages/admin/UserRoles";
import BulkStudentUpload from "@/pages/admin/BulkStudentUpload";
import CredentialDashboard from "@/pages/admin/CredentialDashboard";
import AiEnglishQuality from "@/pages/admin/AiEnglishQuality";
import AiEnglishTaxonomy from "@/pages/admin/AiEnglishTaxonomy";
import AiIeltsValidation from "@/pages/admin/AiIeltsValidation";
import AdaptiveDashboard from "@/pages/admin/AdaptiveDashboard";
import AdaptiveStudentDetail from "@/pages/admin/AdaptiveStudentDetail";
import LevelMappingConfig from "@/pages/admin/LevelMappingConfig";
import WhiteLabelBranding from "@/pages/admin/WhiteLabelBranding";
import ScoreApprovalQueue from "@/pages/admin/ScoreApprovalQueue";
import ExamTemplateSelection from "@/pages/admin/ExamTemplateSelection";
import IeltsExamCreate from "@/pages/admin/IeltsExamCreate";
import IeltsSkillConfig from "@/pages/admin/IeltsSkillConfig";
import IeltsContentPool from "@/pages/admin/IeltsContentPool";
import IeltsExamValidation from "@/pages/admin/IeltsExamValidation";
import CustomExamCreate from "@/pages/admin/CustomExamCreate";
import OfficialExamAccess from "@/pages/OfficialExamAccess";
import FaqPage from "@/pages/FaqPage";
import NotFound from "@/pages/NotFound";
import { queryClient } from "@/lib/query-client";
import { Button } from "@/components/ui/button";

function StudentSubscriptionPlaceholder() {
  const navigate = useNavigate();
  return (
    <div className="min-h-screen flex flex-col items-center justify-center gap-4 p-8">
      <p className="text-muted-foreground text-center max-w-sm">Subscription checkout will be available here.</p>
      <Button onClick={() => navigate("/student/dashboard")}>Back to dashboard</Button>
    </div>
  );
}

const App = () => (
  <QueryClientProvider client={queryClient}>
    <TooltipProvider>
      <Toaster />
      <Sonner />
      <BrowserRouter>
        <AuthProvider>
          <Routes>
            {/* Auth routes */}
            <Route path="/login" element={<Login />} />
            <Route path="/register" element={<Register />} />
            <Route path="/verify-email" element={<EmailVerification />} />
            <Route path="/forgot-password" element={<ForgotPassword />} />
            <Route path="/reset-password" element={<ResetPassword />} />
            <Route path="/verify/:verificationHash" element={<ScoreVerification />} />
            {/* Public pages */}
            <Route path="/apply" element={<AdmissionApplication />} />
            <Route path="/exam/access/:token" element={<OfficialExamAccess />} />
            <Route path="/exam/official/:code" element={<OfficialExamAccess />} />
            <Route path="/exam/login/:examId" element={<OfficialExamAccess />} />
            <Route path="/faq" element={<FaqPage />} />

            <Route element={<ProtectedRoute />}>
              <Route path="/onboarding" element={<OnboardingWizard />} />
            </Route>

            {/* Student routes */}
            <Route element={<ProtectedRoute allowedRoles={["student"]} />}>
              <Route path="/student/exam/:examId/session" element={<ExamSession />} />
              <Route path="/student/exam/:examId/status" element={<ExamStatus />} />
              <Route path="/student/placement/test" element={<PlacementTest />} />
              <Route path="/student/subscription" element={<StudentSubscriptionPlaceholder />} />
              <Route element={<StudentLayout />}>
                <Route path="/student/dashboard" element={<StudentDashboard />} />
                <Route path="/student/courses" element={<StudentCourses />} />
                <Route path="/student/courses/:id" element={<StudentCourseDetail />} />
                <Route path="/student/assignments" element={<StudentAssignments />} />
                <Route path="/student/grades" element={<StudentGrades />} />
                <Route path="/student/attendance" element={<StudentAttendance />} />
                <Route path="/student/timetable" element={<StudentTimetable />} />
                <Route path="/student/profile" element={<StudentProfile />} />
                <Route path="/student/subjects" element={<SubjectSelection />} />
                <Route path="/student/diagnostic/:subjectId" element={<DiagnosticTest />} />
                <Route path="/student/proficiency/:subjectId" element={<ProficiencyProfile />} />
                <Route path="/student/plan/:subjectId" element={<LearningPlanPage />} />
                <Route path="/student/topic/:topicId" element={<TopicLearning />} />
                <Route path="/student/subject-registration" element={<SubjectRegistrationPage />} />
                <Route path="/student/courses/:id/chapters/:chapterId" element={<StudentChapterView />} />
                <Route path="/student/discussions" element={<StudentDiscussionBoard />} />
                <Route path="/student/announcements" element={<StudentAnnouncements />} />
                <Route path="/student/messages" element={<StudentMessages />} />
                <Route path="/student/journey" element={<StudentJourney />} />
                <Route path="/student/placement" element={<PlacementBriefing />} />
                <Route path="/student/placement/results" element={<PlacementResults />} />
                <Route path="/student/placement/access" element={<PlacementAccess />} />
                <Route path="/student/exam/:examId/results" element={<ExamResults />} />
                <Route path="/student/course/generate" element={<GapAnalysis />} />
                <Route path="/student/course/ai-english/:courseId" element={<AiEnglishCourse />} />
                <Route path="/student/course/ai-ielts/:courseId" element={<AiIeltsCourse />} />
                <Route path="/student/course/:courseId" element={<CourseDelivery />} />
              </Route>
            </Route>

            {/* Teacher routes */}
            <Route element={<ProtectedRoute allowedRoles={["teacher"]} />}>
              <Route element={<TeacherLayout />}>
                <Route path="/teacher/dashboard" element={<TeacherDashboard />} />
                <Route path="/teacher/courses" element={<TeacherCourses />} />
                <Route path="/teacher/courses/new" element={<CourseBuilder />} />
                <Route path="/teacher/courses/:id/edit" element={<CourseBuilder />} />
                <Route path="/teacher/assignments" element={<TeacherAssignments />} />
                <Route path="/teacher/assignments/:id" element={<TeacherAssignmentDetail />} />
                <Route path="/teacher/attendance" element={<TeacherAttendance />} />
                <Route path="/teacher/students" element={<TeacherStudents />} />
                <Route path="/teacher/timetable" element={<TeacherTimetable />} />
                <Route path="/teacher/courses/:id/chapters" element={<CourseChapters />} />
                <Route path="/teacher/courses/:id/chapters/:chapterId" element={<ChapterDetail />} />
                <Route path="/teacher/courses/:id/workbench" element={<AiWorkbench />} />
                <Route path="/teacher/discussions" element={<TeacherDiscussionBoard />} />
                <Route path="/teacher/announcements" element={<TeacherAnnouncements />} />
                <Route path="/teacher/profile" element={<TeacherProfile />} />
                <Route path="/teacher/course/:courseId/progress" element={<CourseProgress />} />
                <Route path="/teacher/adaptive/settings" element={<AdaptiveSettings />} />
              </Route>
            </Route>

            {/* Admin routes — unified: original platform + LMS + AI */}
            <Route element={<ProtectedRoute allowedRoles={["admin", "corporate", "mastercorporate", "agent", "developer"]} />}>
              <Route element={<AdminLmsLayout />}>
                {/* LMS Dashboard */}
                <Route path="/admin/dashboard" element={<AdminLmsDashboard />} />
                {/* Original platform dashboard */}
                <Route path="/admin/platform" element={<AdminDashboard />} />
                {/* LMS pages */}
                <Route path="/admin/courses" element={<AdminCourses />} />
                <Route path="/admin/students" element={<AdminStudents />} />
                <Route path="/admin/teachers" element={<AdminTeachers />} />
                <Route path="/admin/batches" element={<AdminBatches />} />
                <Route path="/admin/batches/:id" element={<AdminBatchDetail />} />
                <Route path="/admin/timetable" element={<AdminTimetable />} />
                <Route path="/admin/reports" element={<AdminReports />} />
                <Route path="/admin/settings" element={<AdminSettings />} />
                <Route path="/admin/profile" element={<AdminProfileLms />} />
                {/* Original academic pages */}
                <Route path="/admin/assignments" element={<AssignmentsPage />} />
                <Route path="/admin/examsList" element={<ExamsListPage />} />
                <Route path="/admin/exam-structures" element={<ExamStructuresPage />} />
                <Route path="/admin/rubrics" element={<RubricsPage />} />
                <Route path="/admin/generation" element={<GenerationPage />} />
                <Route path="/admin/approval-workflows" element={<ApprovalWorkflowsPage />} />
                {/* Original management pages */}
                <Route path="/admin/users" element={<UsersPage />} />
                <Route path="/admin/entities" element={<EntitiesPage />} />
                <Route path="/admin/classrooms" element={<ClassroomsPage />} />
                {/* Original report pages */}
                <Route path="/admin/student-performance" element={<StudentPerformancePage />} />
                <Route path="/admin/stats-corporate" element={<StatsCorporatePage />} />
                <Route path="/admin/record" element={<RecordPage />} />
                {/* Training */}
                <Route path="/admin/training/vocabulary" element={<VocabularyPage />} />
                <Route path="/admin/training/grammar" element={<GrammarPage />} />
                {/* Support */}
                <Route path="/admin/payment-record" element={<PaymentRecordPage />} />
                <Route path="/admin/tickets" element={<TicketsPage />} />
                <Route path="/admin/settings-platform" element={<SettingsPage />} />
                <Route path="/admin/exam" element={<ExamPage />} />
                <Route path="/admin/exam/create" element={<ExamTemplateSelection />} />
                <Route path="/admin/exam/ielts/create" element={<IeltsExamCreate />} />
                <Route path="/admin/exam/ielts/:examId/skills" element={<IeltsSkillConfig />} />
                <Route path="/admin/exam/ielts/:examId/content" element={<IeltsContentPool />} />
                <Route path="/admin/exam/ielts/:examId/validate" element={<IeltsExamValidation />} />
                <Route path="/admin/exam/custom/create" element={<CustomExamCreate />} />
                <Route path="/admin/taxonomy" element={<TaxonomyManager />} />
                <Route path="/admin/resources" element={<ResourceManager />} />
                {/* Institutional LMS pages */}
                <Route path="/admin/academic-years" element={<AcademicYearManager />} />
                <Route path="/admin/departments" element={<DepartmentManager />} />
                <Route path="/admin/admissions" element={<AdmissionList />} />
                <Route path="/admin/admissions/:id" element={<AdmissionDetail />} />
                <Route path="/admin/admission-register" element={<AdmissionRegisterPage />} />
                <Route path="/admin/exam-sessions" element={<InstitutionalExamSessions />} />
                <Route path="/admin/marksheets" element={<MarksheetManager />} />
                {/* OpenEduCat module pages */}
                <Route path="/admin/student-leave" element={<AdminStudentLeave />} />
                <Route path="/admin/fees" element={<AdminFees />} />
                <Route path="/admin/lessons" element={<AdminLessons />} />
                <Route path="/admin/gradebook" element={<AdminGradebook />} />
                <Route path="/admin/student-progress" element={<AdminStudentProgress />} />
                <Route path="/admin/library" element={<AdminLibrary />} />
                <Route path="/admin/activities" element={<AdminActivities />} />
                <Route path="/admin/facilities" element={<AdminFacilities />} />
                <Route path="/admin/faq" element={<FaqManager />} />
                <Route path="/admin/notification-rules" element={<NotificationRules />} />
                <Route path="/admin/approval-config" element={<ApprovalWorkflowConfig />} />
                <Route path="/admin/roles-permissions" element={<RolesPermissions />} />
                <Route path="/admin/authority-matrix" element={<AuthorityMatrix />} />
                <Route path="/admin/user-roles" element={<UserRoles />} />
                <Route path="/admin/exam/:examId/grading" element={<GradingQueue />} />
                <Route path="/admin/course/configure/:courseId" element={<CourseConfig />} />
                <Route path="/admin/course/:courseId/modules" element={<ModuleBuilder />} />
                <Route path="/admin/entity/students/upload" element={<BulkStudentUpload />} />
                <Route path="/admin/entity/students/credentials" element={<CredentialDashboard />} />
                <Route path="/admin/entity/:entityId/level-mapping" element={<LevelMappingConfig />} />
                <Route path="/admin/entity/:entityId/branding" element={<WhiteLabelBranding />} />
                <Route path="/admin/ai-course/english/:courseId/quality" element={<AiEnglishQuality />} />
                <Route path="/admin/ai-course/english/taxonomy" element={<AiEnglishTaxonomy />} />
                <Route path="/admin/ai-course/ielts/:courseId/validation" element={<AiIeltsValidation />} />
                <Route path="/admin/adaptive/dashboard" element={<AdaptiveDashboard />} />
                <Route path="/admin/adaptive/student/:studentId" element={<AdaptiveStudentDetail />} />
                <Route path="/admin/scores/pending" element={<ScoreApprovalQueue />} />
              </Route>
            </Route>

            {/* Redirects */}
            <Route path="/" element={<Navigate to="/login" replace />} />
            <Route path="/admin" element={<Navigate to="/admin/dashboard" replace />} />
            {/* Legacy route redirects */}
            <Route path="/dashboard/admin" element={<Navigate to="/admin/platform" replace />} />
            <Route path="*" element={<NotFound />} />
          </Routes>
        </AuthProvider>
      </BrowserRouter>
    </TooltipProvider>
  </QueryClientProvider>
);

export default App;
