import React from 'react';

import DragHandleIcon from '@material-ui/icons/DragIndicator';

import { sortableContainer, sortableElement } from 'react-sortable-hoc';
import arrayMove from 'array-move';
import { toast } from 'react-toastify';

const SortableItem = sortableElement(({value}) => (
  <li className='sortableitem'>
    <DragHandleIcon style={{'verticalAlign': 'middle'}} />
    {value.charAt(0).toUpperCase() + value.slice(1)}
  </li>
));
  
const SortableContainer = sortableContainer(({children}) => {
  return <ul className='sortablecontainer'>{children}</ul>;
});

export default class OrderSettings extends React.PureComponent {
  constructor() {
    super();
    this.state = {
      items: JSON.parse(localStorage.getItem('order'))
    };
    this.language = window.language.modals.main.settings;
  }

  onSortEnd = ({oldIndex, newIndex}) => {
    this.setState(({items}) => ({
      items: arrayMove(items, oldIndex, newIndex)
    }));
  }

  reset = () => {
    localStorage.setItem('order', JSON.stringify(['greeting', 'time', 'quote', 'date']));
  
    this.setState({
      items: JSON.parse(localStorage.getItem('order'))
    });

    toast(this.language.toasts.reset);
  }

  componentDidUpdate() {
    localStorage.setItem('order', JSON.stringify(this.state.items));
  }

  render() {
    return (
      <>
        <h2>Order</h2>
        <span className='modalLink' onClick={this.reset}>Reset</span>
        <SortableContainer onSortEnd={this.onSortEnd}>
          {this.state.items.map((value, index) => (
            <SortableItem key={`item-${value}`} index={index} value={value} />
          ))}
        </SortableContainer>
      </>
    );
  }
}
