import * as React from 'react';
import { InputOption } from './InputOption';

export type OnSelection = (item: any) => void;

export interface Props {
  options?: Array<InputOption>;
  defaultSelection?: string;
  labelForEmptyOption?: string;
  onSelection?: OnSelection;
  disabled?: boolean;
  reset?: boolean;
  elmtId?: string;
  elmtName?: string;
}
export interface State {
  selected: string;
  defaultSelection: string;
}

/**
 * A simple drop-down select component.
 *
 * Prop types:
 * options: Array<{ label: string, value: string}> The options to display
 * disabled: boolean: When set to true the component is disabled.
 * defaultSelection: string: The value for the default element to be selected.
 * reset: boolean: When set to true the selection are reset.
 * onChange: function (d: string) {}: Handler for when selections are made.
 */
export class SelectComponent extends React.Component<Props, State> {
  static defaultProps: Props = {
    disabled: false,
    reset: false,
  };

  constructor(props) {
    super(props);
    let defaultSelection = '';
    if ('defaultSelection' in this.props) {
      defaultSelection = this.props.defaultSelection;
    } else {
      if (this.props.options) {
        const options: Array<InputOption> = this.props.options;
        if (options.length > 0) {
          defaultSelection = options[0].value;
        }
      }
    }
    this.state = {
      defaultSelection: defaultSelection,
      selected: defaultSelection,
    };
  }

  componentDidUpdate() {
    if ('reset' in this.props && this.props.reset) {
      if (this.state.selected != this.state.defaultSelection) {
        this.setState({ selected: this.state.defaultSelection });
      }
    }
  }

  onSelection = (e: React.SyntheticEvent) => {
    const value: string = (e.target as HTMLSelectElement).value;
    this.setState({ selected: value });
    if ('onSelection' in this.props) {
      this.props.onSelection(value);
    }
  };

  render() {
    const disabled: boolean =
      'disabled' in this.props ? this.props.disabled : false;
    const selected: string = this.state.selected;
    const options: Array<InputOption> = this.props.options;
    const createOption = (d: InputOption) => {
      return (
        <option value={d.value} key={d.value}>
          {d.label}
        </option>
      );
    };
    const optionElements = options ? options.map(createOption) : null;

    const labelForEmptyOption: string = this.props.labelForEmptyOption
      ? this.props.labelForEmptyOption
      : 'Select type';

    return (
      <div className="mmui-custom-select">
        <div className="mmui-dropdown-toggle" />
        <select
          id={this.props.elmtId}
          name={this.props.elmtName}
          value={selected}
          disabled={disabled}
          onChange={this.onSelection}
        >
          <option value="none">{labelForEmptyOption}</option>
          {optionElements}
        </select>
      </div>
    );
  }
}
