import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { useAuthStore } from './store/auth';
import Login from './pages/Login';

// Admin pages
import AdminDashboard from './pages/dashboard/AdminDashboard';
import Reports from './pages/admin/Reports';
import Settings from './pages/admin/Settings';
import Users from './pages/admin/Users';
import Departments from './pages/admin/Departments';
import Students from './pages/Students';
import Teachers from './pages/Teachers';
import Classes from './pages/Classes';
import Attendance from './pages/Attendance';
import Fees from './pages/Fees';
import Messages from './pages/Messages';
import Events from './pages/Events';
import Profile from './pages/Profile';
import Nav from './components/Nav';
//vale
import NoticeBoard from './pages/admin/NoticeBoard';
import Library from './pages/admin/Library';

// Role-specific dashboards
import TeacherDashboard from './pages/dashboard/TeacherDashboard';
import StudentDashboard from './pages/dashboard/StudentDashboard';
import ParentDashboard from './pages/dashboard/ParentDashboard';

// Student pages
import StudentAssignments from './pages/student/Assignments';
import StudentMyCourses from './pages/student/MyCourses';
import StudentGrades from './pages/student/Grades';
import StudentExams from './pages/student/Exams';

// Teacher pages
import TeacherMyCourses from './pages/teacher/MyCourses';
import TeacherAssignments from './pages/teacher/Assignments';
import TeacherStudents from './pages/teacher/Students';
import { TeacherTools } from './pages/teacher/TeacherTools';

// Parent pages
import ParentCalendar from './pages/parent/Calendar';
import AcademicProgress from './pages/parent/AcademicProgress';
import ParentMessages from './pages/parent/Messages';
import ParentAttendance from './pages/parent/Attendance';
import ParentFees from './pages/parent/Fees';

// Protected Route Component
function ProtectedRoute({ children, allowedRoles }: { children: React.ReactNode; allowedRoles?: string[] }) {
  const { token, user } = useAuthStore();
  
  if (!token) {
    return <Navigate to="/login" replace />;
  }
  
  if (allowedRoles && user && !allowedRoles.includes(user.role)) {
    const roleRoutes: Record<string, string> = {
      admin: '/dashboard/admin',
      principal: '/dashboard/admin',
      hr: '/dashboard/admin',
      bursar: '/dashboard/admin',
      teacher: '/dashboard/teacher',
      student: '/dashboard/student',
      parent: '/dashboard/parent',
    };
    return <Navigate to={roleRoutes[user.role] || '/dashboard/admin'} replace />;
  }
  
  return <>{children}</>;
}

// Main App Layout with Navigation
function AppLayout() {
  const { token, user, logout } = useAuthStore();
  
  if (!token) {
    return (
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route path="*" element={<Navigate to="/login" />} />
      </Routes>
    );
  }
  
  const getDashboardRoute = () => {
    if (!user) return '/dashboard/admin';
    const routes: Record<string, string> = {
      admin: '/dashboard/admin',
      principal: '/dashboard/admin',
      hr: '/dashboard/admin',
      bursar: '/dashboard/admin',
      teacher: '/dashboard/teacher',
      student: '/dashboard/student',
      parent: '/dashboard/parent',
    };
    return routes[user.role] || '/dashboard/admin';
  };
  
  const getRoutes = () => {
    if (!user) return [];
    
    const commonRoles = ['admin', 'teacher', 'student', 'parent', 'principal', 'hr', 'bursar'];
    const adminRoles = ['admin', 'principal'];

    const commonRoutes = [
      { path: '/profile', element: <Profile />, roles: commonRoles },
      { path: '/messages', element: <Messages />, roles: commonRoles },
      { path: '/events', element: <Events />, roles: commonRoles },
      { path: '/students', element: <Students />, roles: adminRoles },
      { path: '/teachers', element: <Teachers />, roles: adminRoles },
      { path: '/classes', element: <Classes />, roles: ['admin', 'teacher', 'principal'] },
      { path: '/attendance', element: <Attendance />, roles: ['admin', 'teacher', 'principal', 'student'] },
    ];
    
    switch (user.role) {
      case 'admin':
        return [
          { path: '/dashboard/admin', element: <AdminDashboard />, roles: ['admin'] },
          { path: '/users', element: <Users />, roles: ['admin'] },
          { path: '/departments', element: <Departments />, roles: ['admin'] },
          { path: '/reports', element: <Reports />, roles: ['admin'] },
          { path: '/settings', element: <Settings />, roles: ['admin'] },
          { path: '/fees', element: <Fees />, roles: ['admin'] },
          // ADDED: NoticeBoard for admin
          { path: '/notice-board', element: <NoticeBoard />, roles: ['admin'] },
          // ADDED: Library for admin
          { path: '/library', element: <Library />, roles: ['admin'] },
          ...commonRoutes,
        ];
      
      case 'principal':
        return [
          { path: '/dashboard/admin', element: <AdminDashboard />, roles: ['principal'] },
          { path: '/users', element: <Users />, roles: ['principal'] },
          { path: '/departments', element: <Departments />, roles: ['principal'] },
          { path: '/teacher-tools', element: <TeacherTools />, roles: ['principal'] },
          { path: '/fees', element: <Fees />, roles: ['principal'] },
          // ADDED: NoticeBoard for principal
          { path: '/notice-board', element: <NoticeBoard />, roles: ['principal'] },
          // ADDED: Library for principal
          { path: '/library', element: <Library />, roles: ['principal'] },
          ...commonRoutes,
        ];

      case 'hr':
        return [
          { path: '/dashboard/admin', element: <AdminDashboard />, roles: ['hr'] },
          { path: '/hr/records', element: <TeacherTools />, roles: ['hr'] }, // Placeholder
          // ADDED: NoticeBoard for hr
          { path: '/notice-board', element: <NoticeBoard />, roles: ['hr'] },
          ...commonRoutes,
        ];

      case 'bursar':
        return [
          { path: '/dashboard/admin', element: <AdminDashboard />, roles: ['bursar'] },
          { path: '/fees', element: <Fees />, roles: ['bursar'] },
          { path: '/notice-board', element: <NoticeBoard />, roles: ['bursar'] },
          ...commonRoutes,
        ];

      case 'parent':
        return [
            { path: '/dashboard/parent', element: <ParentDashboard />, roles: ['parent'] },
            { path: '/fees', element: <ParentFees />, roles: ['parent'] },
            { path: '/calendar', element: <ParentCalendar />, roles: ['parent'] },
            { path: '/academic-progress', element: <AcademicProgress />, roles: ['parent'] },
            { path: '/attendance', element: <ParentAttendance />, roles: ['parent'] },
            { path: '/notice-board', element: <NoticeBoard />, roles: ['parent'] },
          ...commonRoutes,
        ];
      
      case 'teacher':
        return [
          { path: '/dashboard/teacher', element: <TeacherDashboard />, roles: ['teacher'] },
          { path: '/classes', element: <Classes />, roles: ['teacher'] },
          { path: '/attendance', element: <Attendance />, roles: ['teacher'] },
          { path: '/my-courses', element: <TeacherMyCourses />, roles: ['teacher'] },
          { path: '/assignments', element: <TeacherAssignments />, roles: ['teacher'] },
          { path: '/students', element: <TeacherStudents />, roles: ['teacher'] },
          { path: '/teacher-tools', element: <TeacherTools />, roles: ['teacher'] },
          // ADDED: NoticeBoard for teacher
          { path: '/notice-board', element: <NoticeBoard />, roles: ['teacher'] },
          ...commonRoutes,
        ];
      
      case 'student':
        return [
          { path: '/dashboard/student', element: <StudentDashboard />, roles: ['student'] },
          { path: '/my-courses', element: <StudentMyCourses />, roles: ['student'] },
          { path: '/assignments', element: <StudentAssignments />, roles: ['student'] },
          { path: '/exams', element: <StudentExams />, roles: ['student'] },
          { path: '/grades', element: <StudentGrades />, roles: ['student'] },
          { path: '/attendance', element: <Attendance />, roles: ['student'] },
          // ADDED: NoticeBoard for student
          { path: '/notice-board', element: <NoticeBoard />, roles: ['student'] },
          ...commonRoutes,
        ];
      
      default:
        return [];
    }
  };
  
  const routes = getRoutes();
  
  return (
    <div className="flex min-h-screen bg-background text-text">
      <Nav user={user} onLogout={logout} />
      <div className="flex-1 flex flex-col min-w-0 lg:pl-64">
        <main className="flex-1 p-4 md:p-6 lg:p-8 pt-20 lg:pt-8 pb-24 lg:pb-8">
          <Routes>
            <Route path="/" element={<Navigate to={getDashboardRoute()} />} />
            
            {routes.map(({ path, element, roles }) => (
              <Route 
                key={path} 
                path={path} 
                element={
                  <ProtectedRoute allowedRoles={roles}>
                    {element}
                  </ProtectedRoute>
                } 
              />
            ))}
            
            <Route path="*" element={<Navigate to={getDashboardRoute()} />} />
          </Routes>
        </main>
      </div>
    </div>
  );
}

export default function App() {
  return (
    <BrowserRouter>
      <AppLayout />
    </BrowserRouter>
  );
}