import * as React from "react";
import {
  render,
  screen,
  fireEvent,
  cleanup,
  waitFor,
} from "@testing-library/react";
import SectionPreview from "./SectionPreview";
import { HeaderLayouts } from "@sc/plugins/misc/v2/blocks/weblayouts/Headers/types";

const props = {
  label: HeaderLayouts.ONE,
  layout: HeaderLayouts.ONE,
  onAddSection: (layout) => console.log(layout),
};

const testId = "Blocks-AddSectionsTab-SectionPreview";

describe("Rendering --> <SectionPreview /> Tests", () => {
  afterEach(cleanup);

  it(`Should render in the dom`, () => {
    render(<SectionPreview {...props} />);
    expect(screen.queryByTestId(testId)).toBeTruthy();
  });

  test.skip(`Should auto generate an image based on the LayoutType passed in the props`, () => {});

  it(`Should show the previewImage (instead of the auto-generated image) when one is provided in the previewImage props`, () => {
    const image =
      "https://images.unsplash.com/photo-1590076225577-6026a68fea4d";

    render(<SectionPreview {...props} previewImage={image} />);

    expect(screen.queryByTestId(testId).querySelector("img").src).toBe(image);
  });
});

describe("Events --> <SectionPreview /> Tests", () => {
  afterEach(cleanup);

  it(`Should trigger the onAddSection event when the [add to page] button is clicked`, () => {
    const onAddSection = jest.fn();
    const { container } = render(
      <SectionPreview {...props} onAddSection={onAddSection} />
    );
    fireEvent.mouseEnter(screen.getByTestId(testId));
    waitFor(
      () => {
        fireEvent.click(screen.getByText("Add To Page"));
      },
      { container: screen.getByText("Add To Page") }
    );
    expect(onAddSection).toBeCalled();
  });

  it(`Should receive the LayoutType when the onAddSection event is triggered`, () => {
    const onAddSection = jest.fn();
    render(<SectionPreview {...props} onAddSection={onAddSection} />);
    fireEvent.mouseEnter(screen.getByTestId(testId));
    waitFor(
      () => {
        fireEvent.click(screen.getByText("Add To Page"));
      },
      { container: screen.getByText("Add To Page") }
    );
    expect(onAddSection.mock.calls[0][0]).toBe(HeaderLayouts.ONE);
  });
});

describe("Methods --> <SectionPreview /> Tests", () => {
  afterEach(cleanup);

  test.skip(`Should show a popup window with the actual layout displaying when the [preview] button is clicked`, () => {
    render(<SectionPreview {...props} />);
    fireEvent.mouseEnter(screen.getByTestId(testId));

    expect(
      screen.queryByTestId("Blocks-AddSectionsTab-SectionPreview-Preview")
    ).toBeNull();

    waitFor(
      () => {
        fireEvent.click(screen.getByTestId("preview-icon"));
      },
      { container: screen.getByTestId("preview-icon") }
    );
    expect(
      screen.queryByTestId("Blocks-AddSectionsTab-SectionPreview-Preview")
    ).toBeTruthy();
  });
});
