import React, { Component, Fragment } from 'react';
import Select from 'react-select';
import 'react-select/dist/react-select.css';
import axios from 'axios';
import { SortableContainer, SortableElement, SortableHandle, arrayMove } from 'react-sortable-hoc';

const DragHandle = SortableHandle(() => (<td className="acms-admin-table-nowrap item-handle" style={{ cursor: 'pointer' }}><i
  className="acms-admin-icon-sort"
  aria-hidden="true"
/></td>));

const SortableItem = SortableElement(({ item, removeItem }) => (<tr className="acms-admin-sortable-item sortable-item" key={item.id}>
  <DragHandle />
  <td>
    <input type="hidden" name="related[]" value={item.id} />
    {item.title}
    {item.categoryName &&
    <span className="acms-admin-icon-category acms-admin-icon-mute acms-admin-margin-right-mini" style={{ marginLeft: '5px', display: 'inline-block' }}>
      {item.categoryName}
    </span>
    }
    <div className="entryFormRelatedActions">
      <input
        type="button"
        className="acms-admin-btn-admin acms-admin-btn-admin-danger"
        value={ACMS.i18n('related_entry.remove')}
        style={{ marginRight: '5px' }}
        onClick={() => { removeItem(item.id); }}
      />
      <a href={item.url} className="acms-admin-btn-admin" target="_blank" rel="noopener noreferrer">{ACMS.i18n('related_entry.check')}</a>
    </div>
  </td></tr>));

const SortableList = SortableContainer(({ items, removeItem }) => (<tbody>
  {items.map((item, index) => (<SortableItem key={`item-${item.id}`} index={index} item={item} removeItem={removeItem} />))}
</tbody>));

export default class RelatedEntry extends Component {
  constructor(props) {
    super(props);
    this.state = {
      keyword: '',
      options: [],
      list: props.items
    };
  }

  componentWillReceiveProps(props) {
    if (props.items) {
      this.setState({
        list: props.items
      });
    }
  }

  getItems(keyword) {
    if (!keyword) {
      return Promise.resolve({
        options: []
      });
    }
    return axios({
      method: 'GET',
      url: ACMS.Library.acmsLink({
        tpl: 'ajax/edit/autocomplete.json',
        bid: ACMS.Config.bid
      }, false),
      cache: true,
      responseType: 'json',
      params: {
        keyword
      }
    }).then((response) => {
      const data = response.data;
      const maps = data.map(item => Object.assign({}, item, {
        value: item.value + item.id
      }));
      const options = this.filterOption(maps);
      this.setState({
        options
      });
      return { options };
    });
  }

  onChange(target) {
    const { list } = this.state;
    const find = list.find((item) => {
      if (target.id === item.id) {
        return true;
      }
      return false;
    });
    if (find) {
      alert(ACMS.i18n('related_entry.already_registered'));
      return;
    }
    this.setState({
      list: [...list, target]
    });
  }

  onSortEnd({ oldIndex, newIndex }) {
    this.setState({
      list: arrayMove(this.state.list, oldIndex, newIndex)
    });
  }

  removeItem(id) {
    if (!confirm(ACMS.i18n('related_entry.confirm_remove'))) {
      return;
    }
    const { list } = this.state;
    const filtered = list.filter((item) => {
      if (item.id !== id) {
        return true;
      }
      return false;
    });
    this.setState({
      list: filtered
    });
  }

  filterOption(options) {
    const { list } = this.state;
    const filtered = options.filter((option) => {
      const find = list.find((item) => {
        if (item.id === option.id) {
          return true;
        }
        return false;
      });
      if (find) {
        return false;
      }
      return true;
    });
    return filtered;
  }

  render() {
    const { keyword, list, options } = this.state;
    const filteredOptions = this.filterOption(options);
    return (<Fragment>
      <table className="entryFormTable acms-admin-table-entry">
        <tr>
          <th><label htmlFor="entry-related" /></th>
          <td>
            <div className="acms-admin-related-list-wrap">
              <Select.Async
                autosize={false}
                value={keyword}
                options={filteredOptions}
                loadOptions={this.getItems.bind(this)}
                filterOptions={this.filterOption.bind(this, options)}
                closeOnSelect={false}
                onChange={this.onChange.bind(this)}
                onSelectResetsInput={false}
                placeholder={ACMS.i18n('related_entry.placeholder')}
                searchPromptText={ACMS.i18n('related_entry.type_to_search')}
              />
            </div>
          </td>
        </tr>
      </table>
      <table className="adminTable acms-admin-table-sort acms-admin-margin-bottom-small">
        <SortableList items={list} onSortEnd={this.onSortEnd.bind(this)} removeItem={this.removeItem.bind(this)} useDragHandle />
      </table>
      <input type="hidden" name="entry[]" value="related" />
    </Fragment>);
  }
}
