import "@testing-library/jest-dom";

import { parseTheme } from "@ax/helpers";
import type { IUserFormState } from "@ax/modules/Sites/SitesList/WelcomeModal";
import TimezoneStep from "@ax/modules/Sites/SitesList/WelcomeModal/TimezoneStep";
import globalTheme from "@ax/themes/theme.json";

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

// react-timezone-map-select is mocked globally via jest.config.ts moduleNameMapper

const defaultForm: IUserFormState = {
	name: "John Doe",
	username: "johndoe",
	position: "Developer",
	company: "Acme",
	timezone: "Europe/Madrid",
};

const renderTimezoneStep = (props = {}) =>
	render(
		<ThemeProvider theme={parseTheme(globalTheme)}>
			<TimezoneStep
				form={defaultForm}
				setForm={jest.fn()}
				onClickNext={jest.fn()}
				onClickBack={jest.fn()}
				isSaving={false}
				{...props}
			/>
		</ThemeProvider>,
	);

afterEach(cleanup);

describe("TimezoneStep rendering", () => {
	it("should render Back and Save profile buttons", () => {
		renderTimezoneStep();
		expect(screen.getByText("Back")).toBeTruthy();
		expect(screen.getByText("Save profile")).toBeTruthy();
	});

	it("should render the world map", () => {
		renderTimezoneStep();
		expect(screen.getByTestId("world-map-mock")).toBeTruthy();
	});

	it("should render a timezone select", () => {
		renderTimezoneStep();
		expect(screen.getByTestId("select-component")).toBeTruthy();
	});

	it("should disable Save profile button when isSaving is true", () => {
		renderTimezoneStep({ isSaving: true });
		const saveButton = screen.getByText("Saving...").closest("button");
		expect(saveButton).toBeDisabled();
	});

	it("should show Saving... text when isSaving is true", () => {
		renderTimezoneStep({ isSaving: true });
		expect(screen.getByText("Saving...")).toBeTruthy();
	});

	it("should disable Save profile button when timezone is empty", () => {
		renderTimezoneStep({ form: { ...defaultForm, timezone: "" } });
		const saveButton = screen.getByText("Save profile").closest("button");
		expect(saveButton).toBeDisabled();
	});
});

describe("TimezoneStep events", () => {
	it("should call onClickBack when Back button is clicked", () => {
		const onClickBack = jest.fn();
		renderTimezoneStep({ onClickBack });
		fireEvent.click(screen.getByText("Back"));
		expect(onClickBack).toHaveBeenCalledTimes(1);
	});

	it("should call onClickNext when Save profile button is clicked", () => {
		const onClickNext = jest.fn();
		renderTimezoneStep({ onClickNext });
		fireEvent.click(screen.getByText("Save profile"));
		expect(onClickNext).toHaveBeenCalledTimes(1);
	});

	it("should not call onClickNext when isSaving is true", () => {
		const onClickNext = jest.fn();
		renderTimezoneStep({ onClickNext, isSaving: true });
		const saveButton = screen.getByText("Saving...").closest("button");
		saveButton && fireEvent.click(saveButton);
		expect(onClickNext).not.toHaveBeenCalled();
	});
});
