import React from "react";

import { ThemeProvider } from "styled-components";
import { render, cleanup, screen, fireEvent } from "@testing-library/react";
import { parseTheme } from "@ax/helpers";
import "@testing-library/jest-dom";

import ErrorsBanner from "@ax/components/HeadingsPreviewModal/ErrorsBanner";
import type { IHeadingError } from "@ax/components/HeadingsPreviewModal/utils";
import globalTheme from "@ax/themes/theme.json";

afterEach(cleanup);

const mockError: IHeadingError = {
	message: "No H1 in this page",
	description: "Add an H1 tag",
	headingIds: [],
};

const defaultProps = {
	errors: [mockError],
	onSelectHeading: jest.fn(() => jest.fn()),
	isOpen: false,
	setIsOpen: jest.fn(),
	resetKey: 0,
};

const renderComponent = (props = defaultProps) =>
	render(
		<ThemeProvider theme={parseTheme(globalTheme)}>
			<ErrorsBanner {...props} />
		</ThemeProvider>,
	);

describe("ErrorsBanner component rendering", () => {
	it("should render the SEO Alerts header", () => {
		renderComponent();
		expect(screen.getByText("SEO Alerts")).toBeTruthy();
	});

	it("should render the error message from the errors list", () => {
		renderComponent();
		expect(screen.getByText("No H1 in this page")).toBeTruthy();
	});

	it("should render multiple errors", () => {
		const props = {
			...defaultProps,
			errors: [
				{ message: "Error one", description: "Desc", headingIds: [] },
				{ message: "Error two", description: "Desc", headingIds: [] },
			],
		};
		renderComponent(props);
		expect(screen.getByText("Error one")).toBeTruthy();
		expect(screen.getByText("Error two")).toBeTruthy();
	});

	it("should not render when dismissed", () => {
		renderComponent();
		expect(screen.getByText("SEO Alerts")).toBeTruthy();

		const buttons = screen.getAllByRole("button");
		// Close button is the second button in the header (after toggle)
		fireEvent.click(buttons[1]);

		expect(screen.queryByText("SEO Alerts")).toBeNull();
	});
});

describe("ErrorsBanner component events", () => {
	it("should call setIsOpen with true when toggle is clicked and isOpen is false", () => {
		const setIsOpenMock = jest.fn();
		renderComponent({ ...defaultProps, isOpen: false, setIsOpen: setIsOpenMock });

		const buttons = screen.getAllByRole("button");
		// Toggle is the first button in the header
		fireEvent.click(buttons[0]);
		expect(setIsOpenMock).toBeCalledWith(true);
	});

	it("should call setIsOpen with false when toggle is clicked and isOpen is true", () => {
		const setIsOpenMock = jest.fn();
		renderComponent({ ...defaultProps, isOpen: true, setIsOpen: setIsOpenMock });

		const buttons = screen.getAllByRole("button");
		fireEvent.click(buttons[0]);
		expect(setIsOpenMock).toBeCalledWith(false);
	});
});
