import { Select, Card } from 'antd';
import { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { СhangeOfGood } from '.';
import { actionChangeOneGood, actionChangeGoodsInCat, actionImgClear, actionClearFirstImg } from '../action';

const { Option } = Select;

const SelectGood = ({ goods, changeGood, changeGoodsInCat, imgClear, firstImgClear, _idCat }) => {
  const [goodsCat, setGoodsCat] = useState([]);
  const [_id, setId] = useState('');
  const [selectGood, setSelectGood] = useState({});
  const [numbSelectGood, setNumbSelectGood] = useState('');
  const [idCat, setIdCat] = useState('');
  const [nameCat, setNameCat] = useState('');

  useEffect(() => {
    if (goods && goods.goods && selectGood.name !== goods.goods.name) {
      setSelectGood({});
      setNumbSelectGood('');
    }

    if (goods && goods.goods) {
      setGoodsCat(goods.goods);
      setIdCat(goods._id);
      setNameCat(goods.name);
    }
  }, [goods]);

  function handleChange (value) {
    const good = goodsCat.filter((good, index) => {
      if (good._id === value) {
        setNumbSelectGood(index + 1);
      }

      return good._id === value;
    });
    setSelectGood(...good);
    setId(value);
    imgClear();
    firstImgClear();
  }

  function changeGoodInSer (name, description, price, imgId) {
    changeGood(_id, _idCat, name, description, price, imgId);
  }
  function changeIndexGoodInSer (number) {
    if (numbSelectGood !== number && number > 0) {
      const newGoodsCat = [...goodsCat];
      const goodRemuve = newGoodsCat.splice(numbSelectGood - 1, 1)[0];
      newGoodsCat.splice(number - 1, 0, goodRemuve);
      const newGCat = newGoodsCat.map((item) => {
        console.log('itemmmm', item);
        return ({ _id: item._id });
      });
      changeGoodsInCat(idCat, nameCat, newGCat);
    }
  }

  return (
     < >{goods &&
      <Card type="inner" title="Изменить товар">
        <Select
          value={selectGood.name || null}
          placeholder='Выбирите товар'
          style={{ width: 272 }} onChange={handleChange}>
          {goodsCat.map((item, index) =>
          <Option value={item._id} key={item._id}>{`${index + 1} ${item.name}`}</Option>)}
        </Select>
        <СhangeOfGood
          good={selectGood}
          changeGood={changeGoodInSer}
          number={numbSelectGood}
          changeIndexGoodInSer={changeIndexGoodInSer}/>
      </Card>
    }</>
  );
};

const mapStateToProps = (state) => ({
  goods: state.promise.catById?.payload

});

const mapDispatchToProps = {
  changeGood: actionChangeOneGood,
  changeGoodsInCat: actionChangeGoodsInCat,
  imgClear: actionImgClear,
  firstImgClear: actionClearFirstImg
};

const CartChangeGood = connect(mapStateToProps, mapDispatchToProps)(SelectGood);

export default CartChangeGood;
