import React, { useState } from 'react';
import './SwitchGroup.css';

export default function SwitchGroup({ options = [], value = [], title = '', selectAll = false, onChange }) {
  const allOn = options.length > 0 && options.every(o => value.indexOf(o.value) >= 0);

  function toggle(v) {
    const arr = value.slice();
    const idx = arr.indexOf(v);
    if (idx >= 0) arr.splice(idx, 1); else arr.push(v);
    onChange && onChange(arr);
  }
  function toggleAll() {
    onChange && onChange(allOn ? [] : options.map(o => o.value));
  }

  return (
    <div className="kole-switchgroup">
      {(title || selectAll) ? (
        <div className="kole-switchgroup-head">
          <span className="kole-switchgroup-title">{title}</span>
          {selectAll ? (
            <div className={'kole-switch' + (allOn ? ' is-on' : '')} onClick={toggleAll} />
          ) : null}
        </div>
      ) : null}
      {options.map((o, i) => (
        <div className="kole-switch-row" key={i}>
          <div className="kole-switch-text">
            <span className="kole-switch-label">{o.label}</span>
            {o.desc ? <span className="kole-switch-desc">{o.desc}</span> : null}
          </div>
          <div
            className={'kole-switch' + (value.indexOf(o.value) >= 0 ? ' is-on' : '')}
            onClick={() => toggle(o.value)}
          />
        </div>
      ))}
    </div>
  );
}
