// import React from 'react';
// import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
// import Test from './pages/Test';
// import Login from './pages/Login';

// const App: React.FC = () => {
//   return (
//     <Router basename="/react_ui">
//       <Routes>
//         <Route path="/test" element={<Test />} />
//         <Route path="/login" element={<Login />} />
//         <Route path="*" element={<Navigate to="/test" replace />} />

//       </Routes>
//     </Router>
//   );
// };

// export default App;

import React, { useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate, useLocation } from 'react-router-dom';
import Login from './pages/Login';
import Dashboard from './pages/Dashboard';
import ModernDashboard from './pages/ModernDashboard';
import WoFeedbackPage from './pages/WoFeedbackPage';
import UsersList from './pages/UsersList';
import EventsList from './pages/EventsList';
import AssetList from './pages/AssetList';
import AssetDetail from './pages/AssetDetail';
import WorkOrderList from './pages/WorkOrderList';
import WorkOrderDetail from './pages/WorkOrderDetail';
import AssetMaintenanceList from './pages/AssetMaintenanceList';
import AssetMaintenanceDetail from './pages/AssetMaintenanceDetail';
import PPMList from './pages/PPMList';
import PPMDetail from './pages/PPMDetail';
import PPMPlanner from './pages/PPMPlanner';
import PPMPlannerList from './pages/PPMPlannerList';
import PPMPlannerDetail from './pages/PPMPlannerDetail';
import MaintenanceCalendarPage from './pages/MaintenanceCalendarPage';
import YearlyPPMPlannerPage from './pages/YearlyPPMPlannerPage';
import ActiveMap from './pages/ActiveMap';
import AppEntry from './components/AppEntry';
import ItemList from './pages/ItemList';
import ItemDetail from './pages/ItemDetail';
import ComingSoon from './pages/ComingSoon';
import Sidebar from './components/Sidebar';
import Header from './components/Header';
import { useLanguage } from './contexts/LanguageContext';
import { SidebarLayoutProvider, useSidebarLayout } from './contexts/SidebarLayoutContext';
import IssueList from './pages/IssueList';
import IssueDetail from './pages/IssueDetail';
import MaintenanceTeamList from './pages/MaintenanceTeamList';
import MaintenanceTeamDetail from './pages/MaintenanceTeamDetail';
import UserProfilePage from './pages/UserProfilePage';
import { getDefaultRoute, getStoredRoleProfile, isEndUserRole } from './utils/roleAccess';

// Layout with Sidebar and Header
const LayoutWithSidebarInner: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const location = useLocation();
  const { isRTL } = useLanguage();
  const { mobileOpen, closeMobileSidebar } = useSidebarLayout();
  const user = localStorage.getItem('user');
  const userEmail = user ? JSON.parse(user).email : '';

  useEffect(() => {
    const mq = window.matchMedia('(min-width: 1024px)');
    const handleChange = () => {
      if (mq.matches) closeMobileSidebar();
    };
    handleChange();
    mq.addEventListener('change', handleChange);
    return () => mq.removeEventListener('change', handleChange);
  }, [closeMobileSidebar]);

  return (
    <div className="flex h-screen overflow-hidden bg-gray-50 dark:bg-gray-900">
      {mobileOpen && (
        <button
          type="button"
          className="fixed inset-0 z-40 bg-black/50 lg:hidden"
          onClick={closeMobileSidebar}
          aria-label="Close menu"
        />
      )}

      <div
        className={`
          fixed top-0 z-50 h-full transition-transform duration-300 ease-in-out lg:static lg:z-auto lg:translate-x-0
          ${isRTL
            ? `right-0 ${mobileOpen ? 'translate-x-0' : 'translate-x-full'}`
            : `left-0 ${mobileOpen ? 'translate-x-0' : '-translate-x-full'}`
          }
        `}
      >
        <Sidebar userEmail={userEmail} />
      </div>

      <div className="flex min-w-0 flex-1 flex-col overflow-hidden">
        <Header userEmail={userEmail} />
        <div
          key={location.pathname}
          className="flex-1 overflow-y-auto bg-gray-50 dark:bg-gray-900"
        >
          {children}
        </div>
      </div>
    </div>
  );
};

const LayoutWithSidebar: React.FC<{ children: React.ReactNode }> = ({ children }) => (
  <SidebarLayoutProvider>
    <LayoutWithSidebarInner>{children}</LayoutWithSidebarInner>
  </SidebarLayoutProvider>
);

// Protected Route Component
const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const user = localStorage.getItem('user');
  return user ? <>{children}</> : <Navigate to="/login" replace />;
};

const EndUserDashboardGuard: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  if (isEndUserRole(getStoredRoleProfile())) {
    return <Navigate to={getDefaultRoute(getStoredRoleProfile())} replace />;
  }
  return <>{children}</>;
};

const App: React.FC = () => {
  return (
    <Router basename="/asm_app">
      <Routes>
        <Route path="/login" element={<Login />} />
        
        <Route path="/dashboard" element={
          <ProtectedRoute>
            <EndUserDashboardGuard>
              <LayoutWithSidebar><ModernDashboard /></LayoutWithSidebar>
            </EndUserDashboardGuard>
          </ProtectedRoute>
        } />

        <Route path="/wo-feedback" element={<WoFeedbackPage />} />
        <Route path="/work-order-feedback" element={<Navigate to="/wo-feedback" replace />} />
        
        <Route path="/assets" element={
          <ProtectedRoute>
            <LayoutWithSidebar><AssetList /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/assets/:assetName" element={
          <ProtectedRoute>
            <LayoutWithSidebar><AssetDetail /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/work-orders" element={
          <ProtectedRoute>
            <LayoutWithSidebar><WorkOrderList /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/work-orders/:workOrderName" element={
          <ProtectedRoute>
            <LayoutWithSidebar><WorkOrderDetail /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/maintenance" element={
          <ProtectedRoute>
            <LayoutWithSidebar><AssetMaintenanceList /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/maintenance/:logName" element={
          <ProtectedRoute>
            <LayoutWithSidebar><AssetMaintenanceDetail /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/ppm" element={
          <ProtectedRoute>
            <LayoutWithSidebar><PPMList /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/ppm/:ppmName" element={
          <ProtectedRoute>
            <LayoutWithSidebar><PPMDetail /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/ppm-planner" element={
          <ProtectedRoute>
            <LayoutWithSidebar><PPMPlannerList /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/ppm-planner/new" element={
          <ProtectedRoute>
            <LayoutWithSidebar><PPMPlanner /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/ppm-planner/:scheduleName" element={
          <ProtectedRoute>
            <LayoutWithSidebar><PPMPlannerDetail /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/maintenance-calendar" element={
          <ProtectedRoute>
            <LayoutWithSidebar><YearlyPPMPlannerPage /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/maintenance-calendar/month-view" element={
          <ProtectedRoute>
            <LayoutWithSidebar><MaintenanceCalendarPage /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/yearly-ppm-planner" element={
          <ProtectedRoute>
            <LayoutWithSidebar><YearlyPPMPlannerPage /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/active-map" element={
          <ProtectedRoute>
            <LayoutWithSidebar><ActiveMap /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/inventory" element={
          <ProtectedRoute>
            <LayoutWithSidebar><ItemList /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/inventory/:itemName" element={
          <ProtectedRoute>
            <LayoutWithSidebar><ItemDetail /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/users" element={
          <ProtectedRoute>
            <LayoutWithSidebar><UsersList /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/events" element={
          <ProtectedRoute>
            <LayoutWithSidebar><EventsList /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/old-dashboard" element={
          <ProtectedRoute>
            <LayoutWithSidebar><Dashboard /></LayoutWithSidebar>
          </ProtectedRoute>
        } />

        {/* <Route path="/maintenance-team" element={
          <ProtectedRoute>
            <LayoutWithSidebar><ComingSoon title="Maintenance Team" /></LayoutWithSidebar>
          </ProtectedRoute>
        } /> */}
        <Route path="/maintenance-teams" element={
          <ProtectedRoute>
            <LayoutWithSidebar><MaintenanceTeamList /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/maintenance-teams/:teamName" element={
          <ProtectedRoute>
            <LayoutWithSidebar><MaintenanceTeamDetail /></LayoutWithSidebar>
          </ProtectedRoute>
        } />

        <Route path="/procurement" element={
          <ProtectedRoute>
            <LayoutWithSidebar><ComingSoon title="Procurement" /></LayoutWithSidebar>
          </ProtectedRoute>
        } />

        <Route path="/sla" element={
          <ProtectedRoute>
            <LayoutWithSidebar><ComingSoon title="Service Level Agreement (SLA)" /></LayoutWithSidebar>
          </ProtectedRoute>
        } />

        {/* <Route path="/support" element={
          <ProtectedRoute>
            <LayoutWithSidebar><ComingSoon title="Support" /></LayoutWithSidebar>
          </ProtectedRoute>
        } /> */}
        <Route path="/support" element={
          <ProtectedRoute>
            <LayoutWithSidebar><IssueList /></LayoutWithSidebar>
          </ProtectedRoute>
        } />
        
        <Route path="/support/:issueName" element={
          <ProtectedRoute>
            <LayoutWithSidebar><IssueDetail /></LayoutWithSidebar>
          </ProtectedRoute>
        } />

        <Route path="/user-profile" element={
          <ProtectedRoute>
            <LayoutWithSidebar><UserProfilePage /></LayoutWithSidebar>
          </ProtectedRoute>
        } />


        {/* Default redirect */}
        <Route index element={<AppEntry />} />
        <Route path="/" element={<AppEntry />} />
        <Route path="*" element={<Navigate to="/login" replace />} />
      </Routes>
    </Router>
  );
};

export default App;