import * as React from "react";
import { render, screen, cleanup, fireEvent } from "@testing-library/react";
import { mock } from "jest-mock-extended";
import { ThemeProvider } from "styled-components";
import { parseTheme } from "@ax/helpers";
import globalTheme from "@ax/themes/theme.json";
import { TimeField } from "@ax/components";

afterEach(cleanup);

const defaultProps = mock<ITimeFieldProps>();

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

		const timeFieldWrapper = screen.getByTestId("time-field-wrapper");
		expect(timeFieldWrapper).toBeTruthy();
	});

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

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

		const timeFieldWrapper = screen.getByTestId<HTMLInputElement>("time-field-wrapper");
		expect(timeFieldWrapper).toBeTruthy();
	});

	it("should render component with error", () => {
		defaultProps.error = true;

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

		const timeFieldWrapper = screen.getByTestId<HTMLInputElement>("time-field-wrapper");
		expect(timeFieldWrapper).toBeTruthy();
	});

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

		const timeFieldWInput = screen.getByTestId("time-field-input");
		expect(timeFieldWInput).toBeTruthy();
	});
});

describe("onChange events", () => {
	it("should call onChange on change", () => {
		const onChangeMock = defaultProps.onChange as jest.MockedFunction<(value: string) => void>;
		defaultProps.value = "12:30 am";

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

		const input = screen.getByTestId("time-field-input");
		fireEvent.change(input, { target: { value: "12:30 am" } });
		expect(onChangeMock).toHaveBeenCalledWith("12:30 am");
	});

	it("should call onChange on change with no value", () => {
		const onChangeMock = defaultProps.onChange as jest.MockedFunction<(value: string) => void>;
		defaultProps.value = undefined;

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

		const input = screen.getByTestId("time-field-input");
		fireEvent.change(input, { target: { value: "00:00 am" } });
		expect(onChangeMock).toHaveBeenCalledWith("00:00 am");
	});
});

interface ITimeFieldProps {
	value?: string;
	onChange: (value: string) => void;
	error?: boolean;
	disabled?: boolean;
}
