// @flow

import * as React from 'react';
import * as ReactDOM from 'react-dom';

import { connect } from 'react-redux';

import { withRouter } from 'react-router';
import type { RouterHistory } from 'react-router';

import get from 'lodash/get';

import queryString from 'query-string';

// flowlint  untyped-import:off
import Combobox from '@salesforce/design-system-react/components/combobox';
import Icon from '@salesforce/design-system-react/components/icon';
// flowlint  untyped-import:error

import { perfRESTFetch, perfREST_UI_Fetch } from 'store/perfdata/actions';

import { selectPerfState, selectPerfUIStatus } from 'store/perfdata/selectors';
import type { AppState } from 'store';
import type { InitialProps } from 'components/utils';

type Props = {
  onChange: () => void,
  choices: [string, string][],
  defaultValue: [string, string][],
}

type ReduxProps = {
  perfdataUIstate?: { [string]: mixed },
}

const FieldPicker = ({ history, onChange, choices, defaultValue }:
                              Props & ReduxProps & InitialProps)  =>  {
  const columnOptions = () => {
    let columns: [string, string][] = defaultValue;
    let server_column_options: [string, string][] = choices;
    if (server_column_options) {
      columns = server_column_options;
    }
    return columns.map((pair) => ({ id: pair[0], label: pair[1] }));
  }

  let options = columnOptions();

  const changeURL = (data) => {
    debugger;
    history.push({
      pathname: window.location.pathname,
      search: queryStringFromSelection(data.selection)
    });
    if (onChange) onChange();
  };


  return (
    <Combobox
      id="combobox-readonly-multiple"
      events={{
        onRequestRemoveSelectedOption: (event, data) => changeURL(data),
        onSelect:  (event, data) => changeURL(data),
      }}
      labels={{
        placeholder: 'Select Columns',
      }}
      multiple
      options={options}
      selection={getSelectionFromUrl(options)}
      value=""
      variant="readonly"
    />
  );
}

const getSelectionFromUrl = (options) => {
  let oldQueryParams = queryString.parse(window.location.search);
  let included_field_names = oldQueryParams["include_fields"];
  if (included_field_names != null) {
    if (!Array.isArray(included_field_names)) {
      included_field_names = [included_field_names];
    }
    // this is for flow's benefit
    let indexOf = included_field_names.indexOf.bind(included_field_names);

    let included_options = options.filter((option) => indexOf(option.id) >= 0);
    return included_options;
  }
}

const queryStringFromSelection = (selection: Array<{id: string}>) => {
  let include_fields = selection.map((selection) => selection.id);
  let newQueryParams = { include_fields };
  let oldQueryParams = queryString.parse(window.location.search);
  let qs = queryString.stringify({ ...oldQueryParams, ...newQueryParams });
  return qs;
}


const actions = {
  doPerfREST_UI_Fetch: perfREST_UI_Fetch,
};

const ConnectedFieldPicker: React.ComponentType<Props> = connect(null, actions)(
  withRouter(FieldPicker),
);

export default ConnectedFieldPicker;
@@ -771,16 +771,24 @@
 hange: (
+string%5B%5D
 ) =%3E voi
@@ -841,93 +841,125 @@
 ue: 
-%5B
 string
-,
+%5B%5D %7C
  string
-%5D%5B%5D
 ,%0A%7D
+;
 %0A%0Atype 
-ReduxProps = %7B%0A  perfdataUIstate?: %7B %5Bstring%5D: mixed %7D,%0A%7D
+SLDSChoiceOption = %7B%0A  id: string,%0A  label: string,%0A%7D;%0A%0Atype Options = SLDSChoiceOption%5B%5D
 %0A%0Aco
@@ -982,17 +982,8 @@
 = (%7B
- history,
  onC
@@ -1017,557 +1017,270 @@
 e %7D:
-%0A                              Props & ReduxProps & InitialProps)  =%3E  %7B%0A  const columnOptions = () =%3E %7B%0A    let columns: %5Bstring, string%5D%5B%5D = defaultValue;%0A    let server_column_options: %5Bstring, string%5D%5B%5D = choices;%0A    if (server_column_options) %7B%0A      columns = server_column_options;%0A    %7D%0A    return columns.map((pair) =%3E (%7B id: pair%5B0%5D, label: pair%5B1%5D %7D));%0A  %7D%0A%0A  let options = columnOptions();%0A%0A  const changeURL = (data) =%3E %7B%0A    debugger;%0A    history.push(%7B%0A      pathname: window.location.pathname,%0A      search: queryStringFromS
+ Props)  =%3E  %7B%0A  console.assert(choices && choices.length, %22Choices is empty%22, choices);%0A  let options = choices.map((pair) =%3E (%7B id: pair%5B0%5D, label: pair%5B1%5D %7D));;%0A%0A  const onUpdate = (selections : Options) =%3E %7B%0A    let include_fields = selections.map((s
 election
 (dat
@@ -1279,14 +1279,13 @@
 tion
-(data.
+) =%3E 
 sele
@@ -1293,34 +1293,26 @@
 tion
-)%0A    %7D
+.id
 );%0A    
-if (
 onChange
 ) on
@@ -1311,29 +1311,31 @@
 ange
-) onChange();
+(include_fields)
 %0A  %7D;%0A%0A
-%0A
   re
@@ -1458,86 +1458,186 @@
 vent
-, data) =%3E changeURL(data),%0A        onSelect:  (event, data) =%3E changeURL(data
+: mixed,%0A            data: %7Bselection: Options%7D) =%3E onUpdate(data.selection),%0A        onSelect:  (event: mixed,%0A            data: %7Bselection: Options%7D) =%3E onUpdate(data.selection
 ),%0A 
@@ -1780,23 +1780,50 @@
 tion
-FromUrl(options
+ListFromDefaultValue(options, defaultValue
 )%7D%0A 
@@ -1898,160 +1898,117 @@
 tion
-FromUrl = (options) =%3E %7B%0A  let oldQueryParams = queryString.parse(window.location.search);%0A  let included_field_names = oldQueryParams%5B%22include_fields%22%5D
+ListFromDefaultValue = (options, stringOrArrayFromURL) =%3E %7B%0A  let included_field_names = stringOrArrayFromURL
 ;%0A  
@@ -2380,524 +2380,8 @@
 %0A%7D%0A%0A
-const queryStringFromSelection = (selection: Array%3C%7Bid: string%7D%3E) =%3E %7B%0A  let include_fields = selection.map((selection) =%3E selection.id);%0A  let newQueryParams = %7B include_fields %7D;%0A  let oldQueryParams = queryString.parse(window.location.search);%0A  let qs = queryString.stringify(%7B ...oldQueryParams, ...newQueryParams %7D);%0A  return qs;%0A%7D%0A%0A%0Aconst actions = %7B%0A  doPerfREST_UI_Fetch: perfREST_UI_Fetch,%0A%7D;%0A%0Aconst ConnectedFieldPicker: React.ComponentType%3CProps%3E = connect(null, actions)(%0A  withRouter(FieldPicker),%0A);%0A%0A
 expo
@@ -2395,17 +2395,8 @@
 ult 
-Connected
 Fiel

Remove duplicated code from this component.