import React from 'react';

export function ShirtSizeSelector(props) {
  const { shirtFits, perkOption, shirt, fitsAndSizes, updateFitsAndSizes, sizeOptions, perkOptionProperties, hidden} = props;

  let shirtOption = perkOption;
  if (shirt == 'shirt1') {
    shirtOption = 'take-back-internet';
  } else if (shirt == 'shirt2') {
    shirtOption = 'strength-in-numbers';
  }
  let shirtLabel = shirtFits[shirtOption]['friendly-name'];

  const selectFitFieldName = shirt + '-fit';
  const selectSizeFieldName = shirt + '-size';

  const selectNewFit = (event) => {
    const toBeUpdated = event.target.getAttribute('name').split('-');
    const perkToBeUpdated = toBeUpdated[0];
    const perkToBeUpdatedProperty = toBeUpdated[1];
    updateFitsAndSizes(perkToBeUpdated, perkToBeUpdatedProperty, event.target.value);
  }

  // if the element is hidden, we want to set defaults that the civiCRM backend will accept
  // if we don't set those defaults, the civi backend just drops the donation
  // so we use the first fit specified and a size 's', since they should be valid
  let defaultFit;
  let defaultSize;
  if (hidden) {
    defaultFit = (<option value={Object.keys(shirtFits[shirtOption]['fits'])[0]}></option>);
    defaultSize = <option value='s'></option>;
  } else {
    defaultFit = (<option value={null}>Select Fit</option>);
    defaultSize = (<option value={null}>Select Size</option>);
  }

  return (
    <React.Fragment>
      <div style={hidden ? {'display': 'none'} : {}}>
        <div id="selected-perk-fields-label">{shirtLabel}</div>
        <div className="fit-options-div">
          <select name={selectFitFieldName} className="field input fit required" onChange={selectNewFit}>
            {defaultFit}
            {Object.keys(shirtFits[shirtOption]['fits']).map(fit =>
              <option value={fit} key={fit}>
                {shirtFits[shirtOption]['fits'][fit]['friendly-name']}
              </option>
            )}
          </select>
          <select name={selectSizeFieldName} className="field input size required" onChange={selectNewFit}>
            {defaultSize}
            {sizeOptions}
          </select>
        </div>
      </div>
    </React.Fragment>
  );
}
