import React, { useEffect, useState } from 'react';
import { Upload, Button, Space } from 'antd';
import ImgCrop from 'antd-img-crop';
import { connect } from 'react-redux';
import { actionUploadImg, actionGoodById, actionChangeArrInGood, actionImgClear } from '../action';
import { Link } from 'react-router-dom';

const Additional = ({ imgs, upload, _id, goodById, good, saveImg, imgClear }) => {
  const [fileList, setFileList] = useState([]);

  useEffect(() => {
    goodById(_id);
  }, [_id]);

  const onChange = ({ fileList: newFileList }) => {
    setFileList(newFileList); console.log('newFileList', newFileList);
  };

  const onPreview = async file => {
    let src = file.url; console.log('file', file);
    if (!src) {
      src = await new Promise(resolve => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow.document.write(image.outerHTML);
  };
  const onChangeArrImg = () => {
    const newArrImg = [...good.images].map((item) => ({ _id: item._id }));
    for (let i = 0; i < Object.keys(imgs).length; i++) {
      const newImgId = imgs[`${i}`].payload._id;

      newArrImg.push({ _id: newImgId });
      saveImg(good._id, newArrImg);
    }
  };

  const onSave = async () => {
    const newF = [...fileList].map((item) => [item.originFileObj]);
    await newF.map((item, index) => [upload(item, index)]);

    setFileList([]);
  };

  return (
    <div>
      <ImgCrop rotate>
        <Upload
          action=""
          listType="picture-card"
          fileList={fileList}
          onChange={onChange}
          onPreview={onPreview}
        >
          {fileList.length < 4 && '+ Добавить фото'}
        </Upload>
      </ImgCrop>

      <Space direction="vertical">
        <Button type="primary" onClick={onSave}>Закачать</Button>
        <Button type="primary" onClick={() => { onChangeArrImg(); imgClear(); }}>Сохранить</Button>
        <Link to={`/goodAdmin/${_id}`}>
          <Button type="primary" >Просмотреть карточку товара</Button>
        </Link>
      </Space>

    </div>
  );
};

const mapStateToProps = (state) => ({
  imgs: state.img || [],
  good: state.promise.goodById?.payload || {}
});

const mapDispatchToProps = {
  upload: actionUploadImg,
  goodById: actionGoodById,
  saveImg: actionChangeArrInGood,
  imgClear: actionImgClear
};

const AdditionalImages = connect(mapStateToProps, mapDispatchToProps)(Additional);

export default AdditionalImages;
