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

import Toggle from '@ui/components/Toggle';

// Style
let classes = {};
/* istanbul ignore next */
if (typeof window !== 'undefined') classes = require('./style.module.scss');

export const CustomRefinementList = ({ items, refine, onBlur, isOpen, onRefine }) => {
  const [showMore, setShowMore] = useState(false);
  const limit = showMore ? 99 : 10;

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

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

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

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

const RefinementList = connectRefinementList(CustomRefinementList);

CustomRefinementList.propTypes = {
  isOpen: PropTypes.bool,
  items: PropTypes.array,
  onBlur: PropTypes.func,
  onRefine: PropTypes.func,
  refine: PropTypes.func,
};

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

export default RefinementList;
