import * as React from "react";
import RadioField, { IRadioFieldProps } from "@ax/components/Fields/RadioField";
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";
import { mock } from "jest-mock-extended";

afterEach(cleanup);

const defaultProps = mock<IRadioFieldProps>();

describe("RadioField component rendering", () => {
	it("should render the component", () => {
		render(
			<ThemeProvider theme={parseTheme(globalTheme)}>
				<RadioField {...defaultProps} />
			</ThemeProvider>,
		);

		const radioFieldContainer = screen.getByTestId("radio-field-wrapper");

		expect(radioFieldContainer).toBeTruthy();
	});

	it("should render input as checked", () => {
		defaultProps.checked = true;

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

		const radioFieldInput = screen.getByTestId<HTMLInputElement>("radio-field-input");
		expect(radioFieldInput.checked).toEqual(true);
	});

	it("should render input as disabled", () => {
		defaultProps.disabled = true;

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

		const radioFieldInput = screen.getByTestId<HTMLInputElement>("radio-field-input");
		expect(radioFieldInput.disabled).toEqual(true);
	});

	it("should render input with name", () => {
		defaultProps.name = "This is the name";

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

		const radioFieldInput = screen.getByTestId<HTMLInputElement>("radio-field-input");
		expect(radioFieldInput.name).toEqual("This is the name");
	});
});

describe("onClick events", () => {
	it("should not call onChange function", () => {
		defaultProps.checked = false;
		defaultProps.disabled = false;

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

		const radioFieldInput = screen.getByTestId("radio-field-input");
		fireEvent.click(radioFieldInput);
		expect(defaultProps.onChange).not.toHaveBeenCalled();
	});

	it("should call onChange function", () => {
		defaultProps.checked = false;
		defaultProps.onChange = jest.fn();

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

		const radioFieldInput = screen.getByTestId("radio-field-input");
		fireEvent.click(radioFieldInput);
		expect(defaultProps.onChange).toHaveBeenCalledTimes(1);
	});
});
