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 KeywordItem from "@ax/components/KeywordsPreviewModal/KeywordItem";
import globalTheme from "@ax/themes/theme.json";

afterEach(cleanup);

const defaultProps = {
	keyword: "seo",
	count: 3,
	isSelected: false,
	onClick: jest.fn(),
	deleteKeyword: jest.fn(),
};

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

describe("KeywordItem component rendering", () => {
	it("should render the keyword name", () => {
		renderComponent();
		expect(screen.getByText("seo")).toBeTruthy();
	});

	it("should render the keyword usage count", () => {
		renderComponent();
		expect(screen.getByText("3 used")).toBeTruthy();
	});

	it("should render zero usage count", () => {
		renderComponent({ ...defaultProps, count: 0 });
		expect(screen.getByText("0 used")).toBeTruthy();
	});

	it("should render the delete icon action", () => {
		renderComponent();
		expect(screen.getByTestId("icon-action-component")).toBeTruthy();
	});
});

describe("KeywordItem component events", () => {
	it("should call onClick when the keyword item is clicked", () => {
		const onClickMock = jest.fn();
		renderComponent({ ...defaultProps, onClick: onClickMock });

		// The keyword item is a div with role="button"; the icon-action is a <button> inside it
		const buttons = screen.getAllByRole("button");
		const keywordItem = buttons.find((el) => el.tagName === "DIV");
		expect(keywordItem).toBeTruthy();
		fireEvent.click(keywordItem!);
		expect(onClickMock).toBeCalled();
	});

	it("should call deleteKeyword directly when count is zero and delete is clicked", () => {
		const deleteKeywordMock = jest.fn();
		renderComponent({ ...defaultProps, count: 0, deleteKeyword: deleteKeywordMock });

		const deleteButton = screen.getByTestId("icon-action-component");
		fireEvent.click(deleteButton);
		expect(deleteKeywordMock).toBeCalledWith("seo");
	});

	it("should open the delete confirmation modal when count is greater than zero and delete is clicked", () => {
		renderComponent({ ...defaultProps, count: 3 });

		expect(screen.queryByTestId("modal-wrapper")).toBeNull();

		const deleteButton = screen.getByTestId("icon-action-component");
		fireEvent.click(deleteButton);

		expect(screen.getByTestId("modal-wrapper")).toBeTruthy();
	});

	it("should not call onClick when delete button is clicked (stopPropagation)", () => {
		const onClickMock = jest.fn();
		renderComponent({ ...defaultProps, count: 0, onClick: onClickMock });

		const deleteButton = screen.getByTestId("icon-action-component");
		fireEvent.click(deleteButton);
		expect(onClickMock).not.toBeCalled();
	});
});
