import React from "react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { jest } from "@jest/globals";
import CustomAppBar from "../components/CustomAppBar.js";
import { UserProvider } from "../context/UserContext.js";
import { BrowserRouter } from "react-router-dom";

const mockUser = {
  user_first_name: "John",
  user_last_name: "Doe",
  user_email: "john.doe@test.com",
};

const mockPermissions = [{ Path: "/dashboard", Permission_Id: "1" }];

const renderComponent = (props = {}) => {
  // Set up localStorage with user and permissions
  localStorage.setItem("user", JSON.stringify(mockUser));
  localStorage.setItem("permissions", JSON.stringify(mockPermissions));

  const mockHandleDrawerToggle = jest.fn();
  const mockHandleLogout = jest.fn();

  const defaultProps = {
    open: true,
    handleDrawerToggle: mockHandleDrawerToggle,
    handleLogout: mockHandleLogout,
    ...props,
  };

  const result = render(
    <BrowserRouter>
      <UserProvider>
        <CustomAppBar {...defaultProps} />
      </UserProvider>
    </BrowserRouter>
  );

  return { ...result, mockHandleDrawerToggle, mockHandleLogout };
};

describe("CustomAppBar Component", () => {
  beforeEach(() => {
    jest.clearAllMocks();
    localStorage.clear();
  });

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

  it("should render the component", () => {
    renderComponent();
    expect(screen.getByRole("banner")).toBeInTheDocument();
  });

  it("should render user name", () => {
    renderComponent();
    expect(screen.getByText("John Doe")).toBeInTheDocument();
  });

  it("should render drawer toggle button", () => {
    renderComponent();
    const toggleButton = screen.getByTestId("drawer-menu");
    expect(toggleButton).toBeInTheDocument();
  });

  it("should render open menu icon when drawer is open", () => {
    renderComponent({ open: true });
    expect(screen.getByTestId("open-menu")).toBeInTheDocument();
  });

  it("should render close menu icon when drawer is closed", () => {
    renderComponent({ open: false });
    expect(screen.getByTestId("close-menu")).toBeInTheDocument();
  });

  it("should call handleDrawerToggle when toggle button clicked", () => {
    const { mockHandleDrawerToggle } = renderComponent();
    
    const toggleButton = screen.getByTestId("drawer-menu");
    fireEvent.click(toggleButton);
    
    expect(mockHandleDrawerToggle).toHaveBeenCalledTimes(1);
  });

  it("should open profile menu when profile icon clicked", async () => {
    renderComponent();
    
    // Find the profile section and click it
    const profileSection = document.querySelector(".profile-section");
    const profileIcon = profileSection?.querySelector("svg");
    
    if (profileIcon) {
      fireEvent.click(profileIcon);
      
      await waitFor(() => {
        expect(screen.getByText("Logout")).toBeInTheDocument();
      });
    }
  });

  it("should call handleLogout when Logout clicked", async () => {
    const { mockHandleLogout } = renderComponent();
    
    // Open profile menu
    const profileSection = document.querySelector(".profile-section");
    const profileIcon = profileSection?.querySelector("svg");
    
    if (profileIcon) {
      fireEvent.click(profileIcon);
      
      await waitFor(() => {
        expect(screen.getByText("Logout")).toBeInTheDocument();
      });
      
      const logoutButton = screen.getByText("Logout");
      fireEvent.click(logoutButton);
      
      expect(mockHandleLogout).toHaveBeenCalledTimes(1);
    }
  });

  it("should close profile menu when menu is closed", async () => {
    renderComponent();
    
    // Open profile menu
    const profileSection = document.querySelector(".profile-section");
    const profileIcon = profileSection?.querySelector("svg");
    
    if (profileIcon) {
      fireEvent.click(profileIcon);
      
      await waitFor(() => {
        expect(screen.getByText("Logout")).toBeInTheDocument();
      });
      
      // Click away to close
      fireEvent.click(document.body);
      
      await waitFor(() => {
        // Menu should close - account-menu should not be visible
        expect(screen.queryByRole("menu")).not.toBeInTheDocument();
      }, { timeout: 2000 });
    }
  });
});
