import React from 'react';
import { mount } from 'enzyme';

import AlgoliaSearch from '.';
import RefinementList from './components/RefinementList';
import SearchResults from './components/SearchResults';

describe('AlgoliaSearch', () => {
  let node;

  beforeEach(() => {
    const props = {
      appId: 'T28YKFATPY',
      searchApiKey: 'c9c9c6147013bac3d8882019147443e0',
      indexName: 'readme_search_v2',
      projectsMeta: [
        { subdomain: 'testsub', modules: { docs: true, reference: true, custompages: false } },
        { subdomain: 'sub2', modules: { docs: false, reference: true, custompages: false } },
      ],
    };

    const div = document.createElement('div');
    window.domNode = div;
    document.body.appendChild(div);

    node = mount(<AlgoliaSearch {...props} />, { attachTo: window.domNode });
  });

  it('displays the <AlgoliaSearch> element', () => {
    const sbox = node.find('input[type="search"]');
    const tabs = node.find('.Tabs-listItem');

    sbox.instance().value = 'all'; // have to get the node...
    sbox.first().simulate('change'); // have to use the wrapper...
    sbox.first().simulate('input'); // have to use the wrapper...
    tabs.map(tab => tab.simulate('click'));

    expect(node.state().tabFilters).toStrictEqual(['docs', 'reference']);
    expect(node.find('.AlgoliaSearch').hasClass('AlgoliaSearch')).toBe(true);
  });

  it('should whitelist modules based on refinementlist selection', () => {
    const refinementList = node.find(RefinementList);
    refinementList.prop('onRefine')('sub2');

    expect(refinementList).toHaveLength(1);
    expect(node.state().tabFilters).toStrictEqual(['reference']);
  });

  it('should handle refinemenlist onBlur', () => {
    const addListener = jest.fn();
    window.matchMedia = jest.fn().mockReturnValue({ addListener });

    const refinementList = node.find(RefinementList);
    const preventDefault = jest.fn();

    refinementList.prop('onBlur')({ target: {}, preventDefault, stopPropagation: jest.fn() });
    expect(preventDefault).toHaveBeenCalled();
  });

  it('should handle search result reload', () => {
    const searchRes = node.find(SearchResults);
    const resultSpy = jest.spyOn(document, 'querySelector');

    searchRes.prop('onReload')();
    expect(resultSpy).toHaveBeenCalled();
  });

  describe('handleTabChange()', () => {
    it('should return if tab type is object', () => {
      const res = node.instance().handleTabChange({});
      expect(res).toBeUndefined();
    });

    it('should not call setState if tab does not exist in state', () => {
      const stateSpy = jest.spyOn(node.instance(), 'setState');

      node.instance().handleTabChange('test');
      expect(stateSpy).toHaveBeenCalledTimes(0);
    });
  });
});
