import React from "react";
import TextArea from "@ax/components/Fields/TextArea";
import { ThemeProvider } from "styled-components";
import { parseTheme } from "@ax/helpers";
import globalTheme from "@ax/themes/theme.json";
import { render, screen, cleanup, fireEvent } from "@testing-library/react";

afterEach(cleanup);

const props = {
	name: "",
	value: "",
	onChange: jest.fn(),
};

describe("TextArea component rendering", () => {
	test("should render the component with no CheckField", () => {
		render(
			<ThemeProvider theme={parseTheme(globalTheme)}>
				<TextArea {...props} />
			</ThemeProvider>,
		);

		const textAreaComponent = screen.getAllByTestId("text-area-component");
		expect(textAreaComponent).toHaveLength(1);
	});
});

describe("TextArea events", () => {
	test("should call the onChange", () => {
		const setStateMock = jest.fn();
		const useStateMock: any = (useState: string) => [useState, setStateMock];
		jest.spyOn(React, "useState").mockImplementation(useStateMock);

		render(
			<ThemeProvider theme={parseTheme(globalTheme)}>
				<TextArea {...props} />
			</ThemeProvider>,
		);

		const textAreaComponent = screen.getByTestId("text-area-component");
		expect(textAreaComponent).toBeTruthy();
		fireEvent.change(textAreaComponent, { target: { value: "test" } });
		expect(setStateMock).toHaveBeenCalledWith("test");
	});

	test("should call the onBlur", () => {
		const handleValidationMock = jest.fn();
		const defaultProps = {
			name: "name",
			value: "value",
			onChange: jest.fn(),
			handleValidation: handleValidationMock,
		};

		render(
			<ThemeProvider theme={parseTheme(globalTheme)}>
				<TextArea {...defaultProps} />
			</ThemeProvider>,
		);

		const textAreaComponent = screen.getByTestId("text-area-component");

		expect(textAreaComponent).toBeTruthy();
		fireEvent.blur(textAreaComponent, { target: { value: "name" } });
		expect(handleValidationMock).toHaveBeenCalledTimes(1);
		expect(handleValidationMock).toHaveBeenCalledWith("name");
	});
});
