import React from "react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { jest } from "@jest/globals";

// Mock MSAL
const mockInstance = {
  getActiveAccount: jest.fn(() => ({ username: "test@test.com" })),
  logoutRedirect: jest.fn(),
  acquireTokenSilent: jest.fn(() => Promise.resolve({ accessToken: "mock-token" })),
};

const mockAccounts = [{ username: "test@test.com" }];

jest.unstable_mockModule("@azure/msal-react", () => ({
  __esModule: true,
  useMsal: () => ({
    instance: mockInstance,
    accounts: mockAccounts,
  }),
  MsalProvider: ({ children }) => children,
}));

// Mock react-router-dom
jest.unstable_mockModule("react-router-dom", () => ({
  __esModule: true,
  BrowserRouter: ({ children }) => <div data-testid="router">{children}</div>,
  Routes: ({ children }) => <div data-testid="routes">{children}</div>,
  Route: ({ element }) => <div data-testid="route">{element}</div>,
  Outlet: ({ children }) => <div data-testid="outlet">{children}</div>,
  Link: ({ children, to }) => <a href={to}>{children}</a>,
  Navigate: ({ to }) => <div data-testid="navigate">{to}</div>,
  useNavigate: () => jest.fn(),
  useLocation: () => ({ pathname: "/" }),
  useParams: () => ({}),
  useOutletContext: () => ({ permissionId: "1" }),
}));

// Mock UserContext
const mockLogout = jest.fn();
jest.unstable_mockModule("../context/UserContext.js", () => ({
  __esModule: true,
  useUser: () => ({
    user: { user_email: "test@test.com" },
    permissions: [{ Path: "/dashboard", Permission_Id: "1" }],
    logout: mockLogout,
  }),
  UserProvider: ({ children }) => children,
}));

// Mock child components
jest.unstable_mockModule("../components/CustomAppBar.js", () => ({
  __esModule: true,
  default: ({ handleLogout, handleDrawerToggle }) => (
    <div data-testid="custom-appbar">
      <button onClick={handleLogout} data-testid="logout-btn">Logout</button>
      <button onClick={handleDrawerToggle} data-testid="toggle-btn">Toggle</button>
    </div>
  ),
}));

jest.unstable_mockModule("../components/CustomDrawer.js", () => ({
  __esModule: true,
  default: ({ open, handleDrawerToggle }) => (
    <div data-testid="custom-drawer" data-open={open}>
      <button onClick={handleDrawerToggle}>Toggle Drawer</button>
    </div>
  ),
}));

jest.unstable_mockModule("../components/ProtectedRoute.js", () => ({
  __esModule: true,
  default: ({ children }) => <div data-testid="protected-route">{children}</div>,
}));

jest.unstable_mockModule("../pages/Dashboard.js", () => ({
  __esModule: true,
  default: () => <div data-testid="dashboard">Dashboard</div>,
}));

jest.unstable_mockModule("../pages/SignIn.js", () => ({
  __esModule: true,
  default: () => <div data-testid="signin">SignIn</div>,
}));

jest.unstable_mockModule("../pages/Users.js", () => ({
  __esModule: true,
  default: () => <div data-testid="users">Users</div>,
}));

jest.unstable_mockModule("../pages/Monitoring.js", () => ({
  __esModule: true,
  default: () => <div>Monitoring</div>,
}));

jest.unstable_mockModule("../pages/ActivityTable.js", () => ({
  __esModule: true,
  default: () => <div>ActivityTable</div>,
}));

jest.unstable_mockModule("../pages/ManageUsers.js", () => ({
  __esModule: true,
  default: () => <div>ManageUsers</div>,
}));

jest.unstable_mockModule("../pages/ManageRoles/ManageRoles.js", () => ({
  __esModule: true,
  default: () => <div>ManageRoles</div>,
}));

jest.unstable_mockModule("../pages/PageNotFound.js", () => ({
  __esModule: true,
  default: () => <div>PageNotFound</div>,
}));

jest.unstable_mockModule("../pages/Unauthorized.js", () => ({
  __esModule: true,
  default: () => <div>Unauthorized</div>,
}));

jest.unstable_mockModule("../pages/BrowsingHistory.js", () => ({
  __esModule: true,
  default: () => <div>BrowsingHistory</div>,
}));

jest.unstable_mockModule("../pages/ActivityReports/CallDetails.js", () => ({
  __esModule: true,
  default: () => <div>CallDetails</div>,
}));

jest.unstable_mockModule("../pages/ActivityReports/EmployeeWorkingTime.js", () => ({
  __esModule: true,
  default: () => <div>EmployeeWorkingTime</div>,
}));

jest.unstable_mockModule("../pages/ActivityReports/RunningApplicationDetails.js", () => ({
  __esModule: true,
  default: () => <div>RunningApplicationDetails</div>,
}));

jest.unstable_mockModule("../pages/ActivityReports/SystemLoginDetails.js", () => ({
  __esModule: true,
  default: () => <div>SystemLoginDetails</div>,
}));

jest.unstable_mockModule("../pages/ActivityReports/SystemSleepDetails.js", () => ({
  __esModule: true,
  default: () => <div>SystemSleepDetails</div>,
}));

jest.unstable_mockModule("../pages/ActivityReports/Screenshots.js", () => ({
  __esModule: true,
  default: () => <div>Screenshots</div>,
}));

jest.unstable_mockModule("../pages/UserProfile/UserProfile.js", () => ({
  __esModule: true,
  default: () => <div>UserProfile</div>,
}));

jest.unstable_mockModule("../pages/ActivityReportsCharts/ActivityReportsCharts.js", () => ({
  __esModule: true,
  default: () => <div>ActivityReports</div>,
}));

jest.unstable_mockModule("../components/UserLocation.js", () => ({
  __esModule: true,
  default: () => <div>UserLocation</div>,
}));

jest.unstable_mockModule("../components/AuditLogs.js", () => ({
  __esModule: true,
  default: () => <div>AuditLogs</div>,
}));

jest.unstable_mockModule("../pages/GlobalConfig/GlobalConfig.js", () => ({
  __esModule: true,
  default: () => <div>GlobalConfig</div>,
}));

// Mock react-toastify
jest.unstable_mockModule("react-toastify", () => ({
  __esModule: true,
  ToastContainer: () => <div data-testid="toast-container" />,
  toast: {
    success: jest.fn(),
    error: jest.fn(),
  },
}));

// Import after mocks
const { default: MainContainer } = await import("../components/MainContainer.js");

describe("MainContainer Component", () => {
  beforeEach(() => {
    jest.clearAllMocks();
    localStorage.setItem("user", JSON.stringify({ user_email: "test@test.com" }));
    localStorage.setItem("permissions", JSON.stringify([
      { Path: "/dashboard", Permission_Id: "1" },
    ]));
  });

  afterEach(() => {
    localStorage.clear();
  });

  it("renders the main container", () => {
    render(<MainContainer />);
    expect(screen.getByTestId("router")).toBeInTheDocument();
  });

  it("renders CustomAppBar", () => {
    render(<MainContainer />);
    expect(screen.getByTestId("custom-appbar")).toBeInTheDocument();
  });

  it("renders CustomDrawer", () => {
    render(<MainContainer />);
    expect(screen.getByTestId("custom-drawer")).toBeInTheDocument();
  });

  it("renders ToastContainer", () => {
    render(<MainContainer />);
    expect(screen.getByTestId("toast-container")).toBeInTheDocument();
  });

  it("handles logout click", () => {
    render(<MainContainer />);
    
    const logoutBtn = screen.getByTestId("logout-btn");
    fireEvent.click(logoutBtn);
    
    // Verify logout was called
    expect(mockLogout).toHaveBeenCalled();
    expect(mockInstance.getActiveAccount).toHaveBeenCalled();
    expect(mockInstance.logoutRedirect).toHaveBeenCalled();
  });

  it("handles drawer toggle", () => {
    render(<MainContainer />);
    
    const drawerElement = screen.getByTestId("custom-drawer");
    expect(drawerElement).toHaveAttribute("data-open", "true");
    
    const toggleBtn = screen.getByTestId("toggle-btn");
    fireEvent.click(toggleBtn);
    
    // After toggle, drawer should be closed
    expect(drawerElement).toBeInTheDocument();
  });

  it("handles drawer toggle multiple times", () => {
    render(<MainContainer />);
    
    const drawerElement = screen.getByTestId("custom-drawer");
    expect(drawerElement).toHaveAttribute("data-open", "true");
    
    const toggleBtn = screen.getByTestId("toggle-btn");
    
    // Toggle close
    fireEvent.click(toggleBtn);
    expect(drawerElement).toBeInTheDocument();
    
    // Toggle open again
    fireEvent.click(toggleBtn);
    expect(drawerElement).toBeInTheDocument();
  });

  it("renders routes container", () => {
    render(<MainContainer />);
    expect(screen.getByTestId("routes")).toBeInTheDocument();
  });

  it("handleLogout calls logoutRedirect with postLogoutRedirectUri", () => {
    render(<MainContainer />);
    
    const logoutBtn = screen.getByTestId("logout-btn");
    fireEvent.click(logoutBtn);
    
    expect(mockInstance.logoutRedirect).toHaveBeenCalled();
    expect(mockInstance.getActiveAccount).toHaveBeenCalled();
    // Verify the postLogoutRedirectUri is passed
    const callArgs = mockInstance.logoutRedirect.mock.calls[0][0];
    expect(callArgs.postLogoutRedirectUri).toBe("/signin");
  });

  it("handleDrawerToggle toggles open state", () => {
    render(<MainContainer />);
    
    const drawerElement = screen.getByTestId("custom-drawer");
    
    // Initially open
    expect(drawerElement).toHaveAttribute("data-open", "true");
    
    // Click toggle
    fireEvent.click(screen.getByTestId("toggle-btn"));
    
    // Check drawer is still present
    expect(drawerElement).toBeInTheDocument();
  });
});
