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

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

afterEach(cleanup);

const renderImageStep = (props = {}) =>
	render(
		<ThemeProvider theme={parseTheme(globalTheme)}>
			<ImageStep onCropConfirmed={jest.fn()} onSkip={jest.fn()} {...props} />
		</ThemeProvider>,
	);

describe("ImageStep rendering", () => {
	it("should render UploadView initially", () => {
		renderImageStep();
		expect(screen.getByText("Select image")).toBeTruthy();
		expect(screen.queryByTestId("cropper-mock")).toBeFalsy();
	});

	it("should render CropView after image is loaded", async () => {
		renderImageStep();

		const mockResult = "data:image/jpeg;base64,abc123";
		const mockFileReader = {
			onload: null as any,
			readAsDataURL: jest.fn(function (this: any) {
				this.onload({ target: { result: mockResult } });
			}),
		};
		jest.spyOn(global, "FileReader" as any).mockImplementation(() => mockFileReader);

		const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
		const validFile = new File(["content"], "photo.jpg", { type: "image/jpeg" });

		await act(async () => {
			fireEvent.change(fileInput, { target: { files: [validFile] } });
		});

		expect(screen.getByTestId("cropper-mock")).toBeTruthy();
		expect(screen.queryByText("Select image")).toBeFalsy();
	});

	it("should go back to UploadView when Upload new image is clicked", async () => {
		renderImageStep();

		const mockResult = "data:image/jpeg;base64,abc123";
		const mockFileReader = {
			onload: null as any,
			readAsDataURL: jest.fn(function (this: any) {
				this.onload({ target: { result: mockResult } });
			}),
		};
		jest.spyOn(global, "FileReader" as any).mockImplementation(() => mockFileReader);

		const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
		await act(async () => {
			fireEvent.change(fileInput, { target: { files: [new File([""], "photo.jpg", { type: "image/jpeg" })] } });
		});

		await act(async () => {
			fireEvent.click(screen.getByText("Upload new image"));
		});

		expect(screen.getByText("Select image")).toBeTruthy();
	});
});
