import * as redux from "react-redux";
import store from "../../store";
import { Router } from "react-router-dom";
import history from "../../store/utils/history";
import { mockState } from "../../mockState";
import { render } from "@testing-library/react";
import PatternsPage from "../../pages/PatternsPage/PatternsPage";
import * as api from "../../request/patternsRequest";
import { runSaga } from "redux-saga";
import { FETCH_PATTERNS_REQ } from "../../store/actions/patterns/patternsActionConstants";
import ColorModeProvider from "../../context/ColorModeContext";
import * as fc from "../../store/saga/patternsSaga";
import { setFilteredPatterns, setPatterns } from "../../store/actions/patterns/patternsActions";
import { setPattern } from "../../store/actions/pattern/patternActions";
import { setPatternApplicants } from "../../store/actions/patternApplicants/patternApplicantsActions";

describe("Patterns reducer tests", () => {
  const cont = (
    <redux.Provider store={store}>
      <Router history={history}>
        <ColorModeProvider>
          <PatternsPage />
        </ColorModeProvider>
      </Router>
    </redux.Provider>
  );

  let spyOnUseSelector;
  let spyOnUseDispatch;
  let mockDispatch;

  beforeEach(() => {
    spyOnUseSelector = jest.spyOn(redux, "useSelector");
    spyOnUseSelector.mockReturnValueOnce(mockState.patterns);

    spyOnUseDispatch = jest.spyOn(redux, "useDispatch");
    mockDispatch = jest.fn();
    spyOnUseDispatch.mockReturnValue(mockDispatch);
  });

  afterEach(() => {
    jest.restoreAllMocks();
  });

  it("Should dispatch get patterns request when rendered", () => {
    render(cont);
    expect(mockDispatch).toHaveBeenCalledWith({
      type: FETCH_PATTERNS_REQ,
    });
  });

  it("Should load and handle patterns in case of success", async () => {
    const dispatchedActions = [];

    const mockedCall = { data: mockState.patterns.patterns };
    api.getAllPatterns = jest.fn(() => Promise.resolve(mockedCall));

    const fakeStore = {
      getState: () => mockState.patterns.patterns,
      dispatch: (action) => dispatchedActions.push(action),
    };

    await runSaga(fakeStore, fc.getPatterns, {}).done;
    expect(api.getAllPatterns.mock.calls.length).toBe(1);
    expect(dispatchedActions).toContainEqual(setPatterns(mockedCall.data));
});

  it("Should load and handle pattern by id in case of success", async () => {
    const dispatchedActions = [];
    const id = 1;

    const filteredData = mockState.patterns.patterns.filter(
      (pattern) => pattern.id === id
    );

    const mockedCall = { data: filteredData };
    api.getPatternById = jest.fn(() => Promise.resolve(mockedCall));

    const fakeStore = {
      getState: () => mockState.patterns.patterns,
      dispatch: (action) => dispatchedActions.push(action),
    };

    await runSaga(fakeStore, fc.getPattern, { payload: id }).done;
    expect(api.getPatternById.mock.calls.length).toBe(1);
    expect(dispatchedActions).toContainEqual(setPattern(mockedCall.data));
});

  it("Should load and handle pattern applicants in case of success", async () => {
    const dispatchedActions = [];
    const id = 1;

    const filteredData = mockState.patterns.patterns.filter(
      (pattern) => pattern.id === id
    );

    const mockedCall = {
      data: {
        ...filteredData[0].selectionLevel.selectionProcesses[0].applicant,
      },
    };
    api.getPatternApplicantsById = jest.fn(() => Promise.resolve(mockedCall));

    const fakeStore = {
      getState: () => mockState.patterns.patterns,
      dispatch: (action) => dispatchedActions.push(action),
    };

    await runSaga(fakeStore, fc.getPatternApplicants, { payload: id }).done;
    expect(api.getPatternApplicantsById.mock.calls.length).toBe(1);
    expect(dispatchedActions).toContainEqual(setPatternApplicants(mockedCall.data));
});

  it("Should load and handle filtered patterns in case of success", async () => {
    const dispatchedActions = [];
    const filters = {
      fromDate: new Date("2-2-2021"),
      toDate: new Date("3-3-2023"),
      selectionLevels: [1, 2],
    };

    const filteredData = mockState.patterns.patterns.filter(
      (pattern) =>
        pattern.createdAt >= filters.fromDate &&
        pattern.createdAt <= filters.toDate
    );

    const mockedCall = {
      data: filteredData,
    };
    api.getFilteredPatterns = jest.fn(() => Promise.resolve(mockedCall));

    const fakeStore = {
      getState: () => mockState.patterns.patterns,
      dispatch: (action) => dispatchedActions.push(action),
    };

    await runSaga(fakeStore, fc.filterPatterns, filters).done;
    expect(api.getFilteredPatterns.mock.calls.length).toBe(1);
    expect(dispatchedActions).toContainEqual(setFilteredPatterns(mockedCall.data));
});
});
