import React from "react";
import { ActionMeta, ValueType } from "react-select";
import CreatableSelect from "react-select/creatable";

type CreatableMultiSelectProps = {
  options: Set<string>; // available choices
  values: Set<string>; // current selections
  onChange: (values: Set<string>) => void;
};

type Option = {
  value: string;
  label: string;
};

const convertStringToOption = (value: string) => {
  return { value, label: value };
};

// bugbug: converts "DJ" to "Dj"
const toTitleCase = (s: string) => {
  return s.replace(
    /\w\S*/g,
    (m: string) => m.charAt(0).toUpperCase() + m.substr(1).toLowerCase()
  );
};

export default class CreatableMultiSelect extends React.Component<CreatableMultiSelectProps> {
  handleChange = (value: ValueType<Option>, action: ActionMeta) => {
    const values = value as Array<Option>; // could be a single Option for some types of action
    const capitalizedSortedValues = values
      .map((o) => toTitleCase(o.value))
      .sort();
    const uniqueValues = new Set<string>(capitalizedSortedValues);
    this.props.onChange(uniqueValues);
  };

  render() {
    const options = Array.from(this.props.options).map(convertStringToOption);
    const value = Array.from(this.props.values).map(convertStringToOption);

    return (
      <CreatableSelect<Option>
        isMulti
        isClearable
        value={value}
        onChange={this.handleChange}
        options={options}
      />
    );
  }
}
