import * as React from "react";
import {
  render,
  screen,
  fireEvent,
  cleanup,
  waitFor,
} from "@testing-library/react";
import AddSectionsTab from "./AddSectionsTab";

import { propsData } from "./AddSectionsTab.stories";

const testId = "Blocks-AddSectionsTab";

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

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

  it(`Should show a list of section previews, the number of previews shown should match the number of sections provided in the sections array`, () => {
    render(<AddSectionsTab {...propsData} />);
    expect(
      screen.queryAllByTestId("Blocks-AddSectionsTab-SectionPreview").length
    ).toEqual(propsData.sections.length);
  });

  it(`Should show a list of categories (as determined by the category array in the props) that the user can filter through`, () => {
    render(<AddSectionsTab {...propsData} />);
    expect(
      screen.queryAllByTestId("Blocks-AddSectionsTab-Category").length
    ).toEqual(propsData.categories.length);
  });
});

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

  it(`Should trigger the onAddSection event when one of the section preview [add to page] buttons are clicked`, () => {
    const index = 0;
    const onAddSection = jest.fn();

    render(<AddSectionsTab {...propsData} onAddSection={onAddSection} />);
    const section = screen.queryAllByTestId(
      "Blocks-AddSectionsTab-SectionPreview"
    )[index];
    fireEvent.mouseEnter(section);

    waitFor(
      () => {
        fireEvent.click(section.querySelector("button"));
      },
      { container: section.querySelector("button") }
    );

    expect(onAddSection).toBeCalled();
  });
});

describe("Actions --> <AddSectionsTab /> Tests", () => {
  afterEach(cleanup);

  it(`Should filter the list of layouts being displayed when a category chip is toggled`, () => {
    render(<AddSectionsTab {...propsData} />);
    const index = 0;
    fireEvent.click(
      screen.queryAllByTestId("Blocks-AddSectionsTab-Category")[index]
        .firstChild
    );
    expect(
      screen.queryAllByTestId("Blocks-AddSectionsTab-SectionPreview").length
    ).toEqual(3);
  });

  test.skip(`Should filter the list of layouts being displayed when the search text field is typed in`, () => {
    render(<AddSectionsTab {...propsData} />);
    fireEvent.change(screen.getByTestId(testId).querySelector("input"), {
      target: { value: "Header 03" },
    });
    expect(
      screen.queryAllByTestId("Blocks-AddSectionsTab-SectionPreview").length
    ).toEqual(1);
  });
});
