import React, { Component } from 'react';
import { SortableContainer, SortableElement } from 'react-sortable-hoc';
import { arrayMoveImmutable } from 'array-move';
import { Card, Button } from 'antd';
import { ImgGood } from '.';

const SortableItem = SortableElement(({ value: { _id, url, onSave } }) =>
  <li className='liSortTable'>
    <Card>
      <ImgGood url={url} />
      <Button onClick={onSave}>Сохранить</Button>
    </Card>
  </li>);

const SortableList = SortableContainer(({ items, idGood, onSave, onChangeImagesOnSer }) => {
  return (
    <>
      <ul className='sortTablelist' >
        {items.map((value, index) => (
          <SortableItem key={`item-${index}`} index={index} value={
            {
              _id: value._id,
              url: value.url,
              onSave: () => onSave(value._id)
            }
        } />
        ))}
      </ul>
      <Button type="primary" block onClick={onChangeImagesOnSer}>Сохранить на сервере</Button>
    </>
  );
});

class SortableComponent extends Component {
  state = {
    items: this.props.images,
    idGood: this.props.idGood,
    clearUpLoad: this.props.clearUpLoad
  };

  getState =() => console.log('this.state', this.state)

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

  onChangeImagesOnSer = () => {
    const arrImagesForSave = this.state.items.map((item) => ({ _id: item._id }));
    this.props.onChangeArrInGood(this.state.idGood, arrImagesForSave);
  }

  onSave = (idImg) => {
    const newArrImgs = this.state.items.map((item) => {
      if (idImg === item._id) {
        return {
          _id: this.props.upLoad._id,
          url: this.props.upLoad.url
        };
      };

      return item;
    });

    this.setState(() => ({ items: newArrImgs }));

    this.state.clearUpLoad();
  }

  render () {
    return (
      <SortableList
        axis="xy"
        items={this.state.items}
        idGood={this.state.idGood}
        onSortEnd={this.onSortEnd}
        onSave={this.onSave}
        onChangeImagesOnSer={this.onChangeImagesOnSer}
    />);
  }
}

export default SortableComponent;
