import * as React from 'react';
import * as _ from 'lodash';
import { LexEdit } from './LexEdit';
import {
  Input,
  Dropdown,
} from 'semantic-ui-react';
const { Flex } = require('reflexbox');

// container component
export class LexEditor extends React.Component<any, any> {
  public render() {
    let searchMeta = this.props.fieldMetaMap[this.props.searchState.searchType];
    let searchText = this.props.searchState.searchValue;
    let matchedEntries = _.chain(this.props.allEntries)
      .filter((q: any) => searchMeta.get(q) === searchText)
      .take(10)
      .value();
    let { fieldMetaMap, save, saveXMLBackend } = this.props;
    return (
      <div>
        <LexSearch
          {...this.props}
        />
        <LexMatches
          {...{ fieldMetaMap, save, saveXMLBackend }}
          matchedEntries={matchedEntries}
          selectionMeta={this.props.selectFields}
          searchText={searchText}
          searchMeta={searchMeta}
        />
      </div>
    );
  }
}

class LexSearch extends React.Component<any, any> {
  public render() {
    let dropOptions = _.keys(this.props.fieldMetaMap).map((k, i, c) => {
      return { key: i, value: k, text: _.capitalize(k) };
    });
    return (
      <div>
        <Dropdown
          options={dropOptions}
          onChange={(e, d) => this.handleChange(d, true)}
          value={this.props.searchState.searchType}
          compact={true}
          selection={true}
        />
        <Input
          type="text"
          placeholder="Search input"
          dir="auto"
          value={this.props.searchState.searchValue}
          icon="filter"
          onChange={(e, d) => this.handleChange(d, false)}
        />
      </div>
    );
  }

  private handleChange(e: any, t: boolean) {
    if (t) {
      this.props.searchForType(e.value);
    } else {
      this.props.searchForValue(e.value);
    }
  }
}

function LexMatches(params: any) {
  const selectMode = (props: any) => {
    if (props.searchText === '') {
      return (
        <div>
          <h4>Empty</h4>
          Type something in the searchbar.
        </div>
      );
    } else {
      let editEntries = props.matchedEntries.map((mObj: any) => {
        let uniqueKey = mObj.guid[0] + '#' + mObj.$.id;
        return (
          <LexEdit
            {...props}
            key={uniqueKey}
            lexItem={mObj}
            selectionMeta={props.selectionMeta}
            existing={true}
          />
        );
      });
      let addProps = props.searchMeta.set({}, props.searchText);
      let addEntry = (
        <LexEdit
          {...props}
          key={props.searchText}
          lexItem={addProps}
          selectionMeta={props.selectionMeta}
          existing={false}
        />
      );
      editEntries.push(addEntry);
      return editEntries;
    }
  };
  // const debouncedSelect = _.throttle(selectMode,10000,{leading:true});

  return (
    <Flex wrap={true}>
      {selectMode(params)}
    </Flex>
  );
}
