import { Toaster as SonnerToast } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { BrowserRouter, Routes, Route, Outlet, Navigate, useLocation } from "react-router-dom";
import { useEffect } from "react";
import { AuthProvider, RequireAuth, useAuth } from "./lib/auth-context";
import ApiConnectionAlert from "./components/ApiConnectionAlert";
import QuickAccessWrapper from "./components/QuickAccessWrapper";
import Index from "./pages/Index";
import Login from "./pages/login";
import Dashboard from "./pages/dashboard";
import Projects from "./pages/projects";
import NewProject from "./pages/new-project";
import ProjectEdit from "./pages/project-edit";
import ProjectDetail from "./pages/project-detail";
import Teams from "./pages/teams";
import Backlog from "./pages/backlog";
import LandingPage from "./pages/LandingPage";
import Issues from "./pages/issues";
import NewIssue from "./pages/new-issue";
import IssueDetail from "./pages/issue-detail";
import IssueEdit from "./pages/issue-edit";
import Tasks from "./pages/tasks";
import TimeLogs from "./pages/time-logs";
import CalendarPage from "./pages/calendar";
import Reports from "./pages/reports";
import Messages from "./pages/messages";
import NotFound from "./pages/NotFound";
import Employees from "./pages/employees";
import EmployeeRegister from "./pages/employee-register";
import EmployeeDetail from "./pages/employee-detail";
import EmployeeEdit from "./pages/employee-edit/[id]";
import Roles from "./pages/roles";
import Permissions from "./pages/permissions";
import RolePermissions from "./pages/role-permissions";
import Features from "./pages/features";
import RoleFeatures from "./pages/role-features";
import Deliverables from "./pages/deliverables";
import NewDeliverable from "./pages/new-deliverable";
import DeliverablePage from "./pages/deliverable";
import DeliverableEdit from "./pages/deliverable-edit";
import Attendance from "./pages/attendance";
import { ThemeProvider } from "@/components/ThemeProvider";
import TaskForm from "@/pages/task-form";
import Settings from "@/pages/settings";
import Register from "@/pages/register";
import PrivateRoute from "@/components/PrivateRoute";
import Layout from "@/components/layout/layout";
import NewTaskPage from "@/pages/new-task";
import EditTaskPage from "@/pages/edit-task";
import TaskDetailPage from "@/pages/task-detail";
import DeliverableDetails from "@/pages/deliverable-details";
import Leaves from "@/pages/leaves";
import LeavesAdmin from "@/pages/leaves-admin";
import LeaveTypes from "@/pages/leave-types";
import LeaveBalances from "@/pages/leave-balances";
import MonthlyLeaveReport from "@/pages/monthly-leave-report";
import TodosPage from "@/pages/todos";
import Holidays from "@/pages/holidays";
// Bug Module Imports
import Bugs from "@/pages/bugs";
import BugDetailPage from "@/pages/bug-detail";
import NewBug from "@/pages/new-bug";
import EditBug from "@/pages/edit-bug";
// Production Bug Module Imports
import ProductionBugs from "@/pages/production-bugs";
import ProductionBugDetailPage from "@/pages/production-bug-detail";
// Test Cases Module Imports
import TestCases from "@/pages/test-cases";
import TestCaseForm from "@/pages/test-case-form";
import TestCaseDetailPage from "@/pages/test-case-detail";
import EditTestCase from "@/pages/edit-test-case";
// Appraisal Module Imports
import AppraisalCycles from "@/pages/appraisal/cycles";
import AssessmentAreas from "@/pages/appraisal/assessment-areas";
import Competencies from "@/pages/appraisal/competencies";
import MyAppraisals from "@/pages/appraisal/my-appraisals";
import AppraisalView from "@/pages/appraisal/appraisal-view";
import ManagerDashboard from "@/pages/appraisal/manager-dashboard";
import RoleQuestions from "@/pages/appraisal/role-questions";
import HrRemarks from "@/pages/appraisal/hr-remarks";
import ManagementRemarks from "@/pages/appraisal/management-remarks";
// Meeting Room Booking Module Imports
import MeetingRoomsPage from "@/pages/meeting-room/rooms";
import BookRoomPage from "@/pages/meeting-room/book";
import BookingsPage from "@/pages/meeting-room/bookings";
import EditBookingPage from "@/pages/meeting-room/edit-booking";
import BookingDetailPage from "@/pages/meeting-room/booking-detail";
import RoomDetailPage from "@/pages/meeting-room/room-detail";
// Communication Trail Module Import
import Communications from "@/pages/communications";
import ForgotPassword from "@/pages/forgot-password";
import ResetPassword from "@/pages/reset-password";
import EmployeeDetailsEdit from "./pages/employee-details-edit";
import MyProfile from "@/pages/my-profile";
// Employee Projects Module Imports
import EmployeeProjects from "./pages/employee-projects";
import EmployeeProjectsList from "./pages/employee-projects-list";
import ResourceAllocation from "./pages/resource-allocation";
// Asset Management Module Imports
import Assets from "./pages/asset-management/Assets";
import AssetDetails from "./pages/asset-management/AssetDetails";
import SystemDetails from "./pages/asset-management/SystemDetails";
import Assignments from "./pages/asset-management/Assignments";
import AssetRequestsPage from "./pages/asset-requests";
import AdminAssetRequestManagement from "./pages/admin/asset-request-management";
// Download App Page
import DownloadApp from "@/pages/download-app";
// Gantt Chart
import GanttChart from "@/pages/gantt-chart";
// PMP (Project Management Plan)
import PMPPage from "@/pages/pmp";
// Health Dashboard
import HealthDashboard from "./pages/health-dashboard";

// Import the date picker fix styles
import "./styles/date-picker-fix.css";

const queryClient = new QueryClient();

// Client redirect component to ensure client users only access production bugs
const ClientRedirect = () => {
  const { userData } = useAuth();
  const location = useLocation();
  
  if (userData?.roleName?.toLowerCase() === "client") {
    const isFromDashboard = location.pathname === "/" || location.pathname === "";
    
    // If coming from dashboard, store this in session storage
    if (isFromDashboard) {
      sessionStorage.setItem('from-dashboard', 'true');
    }
    
    return <Navigate to="/production-bugs" state={{ from: isFromDashboard ? "dashboard" : location.pathname }} replace />;
  }
  
  return <Outlet />;
};

const App = () => {
  // Handle mobile-specific navigation issues
  useEffect(() => {
    // Fix for initial render issue - ensure the correct route is loaded
    const path = window.location.pathname;
    if (path === "/" || path === "") {
      console.log("Initial app load at root path");
    }
    
    // Fix for Capacitor web view
    const handleError = (event: ErrorEvent) => {
      console.error("App error:", event.error);
    };
    
    window.addEventListener('error', handleError);
    
    return () => {
      window.removeEventListener('error', handleError);
    };
  }, []);

  return (
    <QueryClientProvider client={queryClient}>
      <ThemeProvider defaultTheme="light" storageKey="vite-ui-theme">
        <style>
          {`
            /* Fix for black screen with popover/dropdown menus */
            body, #root {
              min-height: 100vh;
              position: relative;
              overflow-x: hidden;
              background-color: var(--background);
              color: var(--foreground);
            }

            .popover-fix {
              position: absolute;
              top: 0;
              left: 0;
              width: 100%;
              height: 100%;
              z-index: -1;
            }

            /* Ensure popover content has proper z-index and background */
            [data-radix-popper-content-wrapper] {
              z-index: 50 !important;
            }

            /* Fix for command dialog styles */
            [cmdk-root] {
              background-color: white !important;
            }

            [data-theme="dark"] [cmdk-root] {
              background-color: hsl(240 10% 3.9%) !important;
            }
            
            /* Fix for floating-ui dropdown */
            .floating-ui-dropdown {
              background-color: white !important;
              border: 1px solid rgba(0, 0, 0, 0.1) !important;
              box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
            }
            
            [data-theme="dark"] .floating-ui-dropdown {
              background-color: hsl(240 10% 3.9%) !important;
              border-color: rgba(255, 255, 255, 0.1) !important;
            }

            /* Fix for toast notifications */
            [data-sonner-toast] {
              background-color: rgb(255, 255, 255) !important;
              border: 1px solid rgba(0, 0, 0, 0.1) !important;
              box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
              opacity: 1 !important;
            }

            [data-theme="dark"] [data-sonner-toast] {
              background-color: rgb(26, 27, 30) !important;
              border-color: rgba(255, 255, 255, 0.1) !important;
            }

            /* Force toast background to be opaque */
            [data-sonner-toast] > div,
            [data-sonner-toast] > div > div {
              background-color: inherit !important;
              opacity: 1 !important;
            }

            /* Target the toast content specifically */
            [data-sonner-toast] [data-type] {
              background-color: inherit !important;
              opacity: 1 !important;
            }

            /* Ensure toast is at the bottom right */
            [data-sonner-toaster] {
              bottom: 16px !important;
              right: 16px !important;
              top: auto !important;
              left: auto !important;
            }
          `}
        </style>
        <div className="popover-fix"></div>
        <TooltipProvider>
          <SonnerToast />
          <BrowserRouter basename="">
            <AuthProvider>
              <ApiConnectionAlert />
              <QuickAccessWrapper />
              <Routes>
                <Route path="/" element={<LandingPage />} />
                <Route path="/dashboard" element={<PrivateRoute />}>
                  <Route index element={<Dashboard />} />
                </Route>
                <Route path="/" element={<PrivateRoute />}>
                  <Route element={<ClientRedirect />}>
                    <Route path="tasks" element={<Tasks />} />
                    <Route path="tasks/new" element={<NewTaskPage />} />
                    <Route path="tasks/:id" element={<TaskDetailPage />} />
                    <Route path="tasks/:id/edit" element={<EditTaskPage />} />
                    <Route path="bugs" element={<Bugs />} />
                    <Route path="bugs/new" element={<NewBug />} />
                    <Route path="bugs/:id" element={<BugDetailPage />} />
                    <Route path="bugs/:id/edit" element={<EditBug />} />
                  </Route>
                  <Route path="production-bugs" element={<ProductionBugs />} />
                  <Route path="production-bugs/new" element={<NewBug defaultType="Production Bug" />} />
                  <Route path="production-bugs/:id" element={<ProductionBugDetailPage />} />
                  <Route path="production-bugs/:id/edit" element={<EditBug />} />
                  <Route path="test-cases" element={<TestCases />} />
                  <Route path="test-cases/new" element={<TestCaseForm />} />
                  <Route path="test-cases/:id" element={<TestCaseDetailPage />} />
                  <Route path="test-cases/:id/edit" element={<EditTestCase />} />
                  <Route path="issues" element={<Issues />} />
                  <Route path="communications" element={
                    <RequireAuth>
                      <Communications />
                    </RequireAuth>
                  } />
                  <Route path="employees" element={<Employees />} />
                  <Route path="attendance" element={<Attendance />} />
                  <Route path="leaves" element={<Leaves />} />
                  <Route path="leaves-admin" element={<LeavesAdmin />} />
                  <Route path="leave-types" element={<LeaveTypes />} />
                  <Route path="leave-balances" element={<LeaveBalances />} />
                  <Route path="monthly-leave-report" element={<MonthlyLeaveReport />} />
                  <Route path="settings" element={<Settings />} />
                </Route>
                <Route path="/login" element={
                  <Login />
                } />
                <Route path="/register" element={<Register />} />
                <Route path="/forgot-password" element={<ForgotPassword />} />
                <Route path="/reset-password" element={<ResetPassword />} />
                <Route path="/download-app" element={<DownloadApp />} />
                <Route path="/health-dashboard" element={
                  <RequireAuth>
                    <HealthDashboard />
                  </RequireAuth>
                } />
                <Route path="/holidays" element={
                  <RequireAuth>
                    <Holidays />
                  </RequireAuth>
                } />
                <Route path="/todos" element={
                  <RequireAuth>
                    <TodosPage />
                  </RequireAuth>
                } />
                <Route path="/meeting-room/rooms" element={
                  <RequireAuth>
                    <MeetingRoomsPage />
                  </RequireAuth>
                } />
                <Route path="/meeting-room/room/:id" element={
                  <RequireAuth>
                    <RoomDetailPage />
                  </RequireAuth>
                } />
                <Route path="/meeting-room/book/:roomId" element={
                  <RequireAuth>
                    <BookRoomPage />
                  </RequireAuth>
                } />
                <Route path="/meeting-room/bookings" element={
                  <RequireAuth>
                    <BookingsPage />
                  </RequireAuth>
                } />
                <Route path="/meeting-room/bookings/:id" element={
                  <RequireAuth>
                    <BookingDetailPage />
                  </RequireAuth>
                } />
                <Route path="/meeting-room/edit-booking/:id" element={
                  <RequireAuth>
                    <EditBookingPage />
                  </RequireAuth>
                } />
                <Route path="/projects" element={
                  <RequireAuth>
                    <Projects />
                  </RequireAuth>
                } />
                <Route path="/gantt-chart" element={
                  <RequireAuth>
                    <GanttChart />
                  </RequireAuth>
                } />
                <Route path="/pmp" element={
                  <RequireAuth>
                    <PMPPage />
                  </RequireAuth>
                } />
                <Route path="/new-project" element={
                  <RequireAuth>
                    <NewProject />
                  </RequireAuth>
                } />
                <Route path="/project/:id" element={
                  <RequireAuth>
                    <ProjectDetail />
                  </RequireAuth>
                } />
                <Route path="/project-edit/:id" element={
                  <RequireAuth>
                    <ProjectEdit />
                  </RequireAuth>
                } />
                <Route path="/teams" element={
                  <RequireAuth>
                    <Teams />
                  </RequireAuth>
                } />
                <Route path="/backlog" element={
                  <RequireAuth>
                    <Backlog />
                  </RequireAuth>
                } />
                <Route path="/new-issue" element={
                  <RequireAuth>
                    <NewIssue />
                  </RequireAuth>
                } />
                <Route path="/issues/new" element={
                  <RequireAuth>
                    <NewIssue />
                  </RequireAuth>
                } />
                <Route path="/issues/edit/:id" element={
                  <RequireAuth>
                    <IssueEdit />
                  </RequireAuth>
                } />
                <Route path="/issues/:id" element={
                  <RequireAuth>
                    <IssueDetail />
                  </RequireAuth>
                } />
                <Route path="/issue/:id" element={
                  <RequireAuth>
                    <IssueDetail />
                  </RequireAuth>
                } />
                <Route path="/issue/edit/:id" element={
                  <RequireAuth>
                    <IssueEdit />
                  </RequireAuth>
                } />
                <Route path="/time-logs" element={
                  <RequireAuth>
                    <TimeLogs />
                  </RequireAuth>
                } />
                <Route path="/calendar" element={
                  <RequireAuth>
                    <CalendarPage />
                  </RequireAuth>
                } />
                <Route path="/reports" element={
                  <RequireAuth>
                    <Reports />
                  </RequireAuth>
                } />
                <Route path="/messages" element={
                  <RequireAuth>
                    <Messages />
                  </RequireAuth>
                } />
                <Route path="/employee-register" element={
                  <RequireAuth>
                    <EmployeeRegister />
                  </RequireAuth>
                } />
                <Route path="/employee/:id" element={
                  <RequireAuth>
                    <EmployeeDetail />
                  </RequireAuth>
                } />
                <Route path="/employee-edit/:id" element={
                  <RequireAuth>
                    <EmployeeEdit />
                  </RequireAuth>
                } />
                <Route path="/employee-details-edit/:id" element={<EmployeeDetailsEdit />} />
                <Route path="/roles" element={
                  <RequireAuth>
                    <Roles />
                  </RequireAuth>
                } />
                <Route path="/permissions" element={
                  <RequireAuth>
                    <Permissions />
                  </RequireAuth>
                } />
                <Route path="/role-permissions" element={
                  <RequireAuth>
                    <RolePermissions />
                  </RequireAuth>
                } />
                <Route path="/features" element={
                  <RequireAuth>
                    <Features />
                  </RequireAuth>
                } />
                <Route path="/role-features" element={
                  <RequireAuth>
                    <RoleFeatures />
                  </RequireAuth>
                } />
                <Route path="/deliverables" element={
                  <RequireAuth>
                    <Deliverables />
                  </RequireAuth>
                } />
                <Route path="/new-deliverable" element={
                  <RequireAuth>
                    <NewDeliverable />
                  </RequireAuth>
                } />
                <Route path="/deliverable/:id" element={
                  <RequireAuth>
                    <DeliverablePage />
                  </RequireAuth>
                } />
                <Route path="/deliverable-details/:id" element={
                  <RequireAuth>
                    <DeliverableDetails />
                  </RequireAuth>
                } />
                <Route path="/deliverable/:id/edit" element={
                  <RequireAuth>
                    <DeliverableEdit />
                  </RequireAuth>
                } />
                <Route path="/deliverable-edit/:id" element={
                  <RequireAuth>
                    <DeliverableEdit />
                  </RequireAuth>
                } />
                <Route path="/appraisals/cycles" element={
                  <RequireAuth>
                    <AppraisalCycles />
                  </RequireAuth>
                } />
                <Route path="/appraisals/assessment-areas" element={
                  <RequireAuth>
                    <AssessmentAreas />
                  </RequireAuth>
                } />
                <Route path="/appraisals/competencies" element={
                  <RequireAuth>
                    <Competencies />
                  </RequireAuth>
                } />
                <Route path="/appraisals/my-appraisals" element={
                  <RequireAuth>
                    <MyAppraisals />
                  </RequireAuth>
                } />
                <Route path="/appraisals/view/:id" element={
                  <RequireAuth>
                    <AppraisalView />
                  </RequireAuth>
                } />
                <Route path="/appraisals/manager-dashboard" element={
                  <RequireAuth>
                    <ManagerDashboard />
                  </RequireAuth>
                } />
                <Route path="/appraisals/role-questions" element={
                  <RequireAuth>
                    <RoleQuestions />
                  </RequireAuth>
                } />
                <Route path="/appraisals/hr-remarks" element={
                  <RequireAuth>
                    <HrRemarks />
                  </RequireAuth>
                } />
                <Route path="/appraisals/management-remarks" element={
                  <RequireAuth>
                    <ManagementRemarks />
                  </RequireAuth>
                } />
                <Route path="/my-profile" element={
                  <RequireAuth>
                    <MyProfile />
                  </RequireAuth>
                } />
                <Route path="/profile" element={
                  <RequireAuth>
                    <MyProfile />
                  </RequireAuth>
                } />
                <Route path="/employee-projects" element={
                  <RequireAuth>
                    <EmployeeProjectsList />
                  </RequireAuth>
                } />
                <Route path="/employee-projects/:id" element={
                  <RequireAuth>
                    <EmployeeProjects />
                  </RequireAuth>
                } />
                <Route path="/employee-projects-list" element={
                  <RequireAuth>
                    <EmployeeProjectsList />
                  </RequireAuth>
                } />
                <Route path="/resource-allocation" element={
                  <RequireAuth>
                    <ResourceAllocation />
                  </RequireAuth>
                } />
                <Route path="/assets" element={
                  <RequireAuth>
                    <Assets />
                  </RequireAuth>
                } />
                <Route path="/assets/:id" element={
                  <RequireAuth>
                    <AssetDetails />
                  </RequireAuth>
                } />
                <Route path="/system-details" element={
                  <RequireAuth>
                    <SystemDetails />
                  </RequireAuth>
                } />
                <Route path="/asset-assignments" element={
                  <RequireAuth>
                    <Assignments />
                  </RequireAuth>
                } />
                <Route path="/asset-requests" element={
                  <RequireAuth>
                    <AssetRequestsPage />
                  </RequireAuth>
                } />
                <Route path="/admin/asset-requests" element={
                  <RequireAuth>
                    <AdminAssetRequestManagement />
                  </RequireAuth>
                } />
                <Route path="*" element={<NotFound />} />
              </Routes>
            </AuthProvider>
          </BrowserRouter>
        </TooltipProvider>
      </ThemeProvider>
    </QueryClientProvider>
  );
};

export default App;
