import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { connectRefinementList } from 'react-instantsearch-dom';
import orderBy from 'lodash/orderBy';

import Toggle from '../../../../components/Toggle';

import classes from './style.module.scss';

export var CustomRefinementList = function CustomRefinementList(_ref) {
  var items = _ref.items,
      refine = _ref.refine,
      onBlur = _ref.onBlur,
      isOpen = _ref.isOpen,
      onRefine = _ref.onRefine;

  var _useState = useState(false),
      showMore = _useState[0],
      setShowMore = _useState[1];

  var limit = showMore ? 99 : 10;

  if (items.length <= 1) return null;

  var blurred = function blurred(event) {
    var currentTarget = event.currentTarget,
        key = event.key,
        shiftKey = event.shiftKey;

    if (key === 'Tab' && !shiftKey && currentTarget.matches(':last-of-type') && typeof onBlur === 'function') onBlur(event);
  };

  var orderedItems = orderBy(items, 'label', 'asc').slice(0, limit);

  return React.createElement(
    'details',
    { className: classes['RefinementList-Col'], open: isOpen },
    React.createElement(
      'summary',
      { className: classes['RefinementList-Header'], tabIndex: -1 },
      'Filters'
    ),
    React.createElement(
      'ol',
      { className: classes.RefinementList },
      orderedItems.map(function (item) {
        return React.createElement(
          'li',
          { key: item.label, className: classes['RefinementList-Item'], onKeyDown: blurred },
          React.createElement(Toggle, {
            checked: item.isRefined,
            className: classes['RefinementList-Toggle'],
            label: item.label,
            onChange: function onChange() {
              refine(item.value);
              onRefine(item.value);
            }
          })
        );
      })
    ),
    items.length > 10 && React.createElement(
      'button',
      { className: classes['RefinementList-Button'], onClick: function onClick() {
          return setShowMore(!showMore);
        }, type: 'button' },
      showMore ? 'Less' : 'More'
    )
  );
};

var RefinementList = connectRefinementList(CustomRefinementList);

CustomRefinementList.propTypes = process.env.NODE_ENV !== "production" ? {
  isOpen: PropTypes.bool,
  items: PropTypes.array,
  onBlur: PropTypes.func,
  onRefine: PropTypes.func,
  refine: PropTypes.func
} : {};

RefinementList.propTypes = {
  attribute: PropTypes.string
};

export default RefinementList;