import classNames from 'classnames';
import intersection from 'lodash.intersection';
import React, { PropTypes } from 'react';

export default function OptionsGroup({ theme, group, changeOption, changeGroup, selecteds }) {
  return (
    <ul
      className={
        classNames(
          'c-options-group',
          theme['c-options-group'],
        )
      }
    >
      <li>
        <button
          className={
            classNames(
              'c-options-group__group-header',
              theme['c-options-group__group-header'],
            )
          }
          onClick={(event) => {
            event.preventDefault();

            if (
              intersection(
                selecteds, group.options,
              ).length === group.options.length
            ) {
              changeGroup(group, false);
            } else {
              changeGroup(group, true);
            }
          }}
        >
          {group.label}
        </button>
      </li>
      {
        group.options.map(option => (
          <li key={option.value}>
            <label
              className={
                classNames(
                  'c-options-group__group-option',
                  theme['c-options-group__group-option'],
                )
              }
              htmlFor={option.value}
            >
              <input
                id={option.value}
                value={option.value}
                type="checkbox"
                onChange={(event) => {
                  const { value, checked } = event.target;
                  const option = group.options.find(o => o.value === value);
                  changeOption(option, checked);
                }}
                checked={selecteds.includes(option)}
              />
              {option.label}
            </label>
          </li>
        ))
      }
    </ul>
  );
}

OptionsGroup.propTypes = {
  theme: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.func,
  ]).isRequired,
  changeOption: PropTypes.func,
  changeGroup: PropTypes.func,
  selecteds: PropTypes.arrayOf(
    PropTypes.shape({
      value: PropTypes.string,
      label: PropTypes.label,
    }),
  ),
  group: PropTypes.shape({
    label: PropTypes.string,
    options: PropTypes.arrayOf(
      PropTypes.shape({
        value: PropTypes.string,
        label: PropTypes.string,
      }),
    ),
  }),
};
