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

const { Option } = Select;

const SelectGood = ({goods, changeGood}) => { console.log('ggggg',goods)
  
  const [goodsCat, setGoodsCat] = useState([]); 
  const [_id, setId] = useState('');
  const [selectGood, setSelectGood] = useState({}); 
  console.log('RENDER======')
  useEffect(() => {
    if(goods && goods.goods && selectGood.name!== goods.goods.name ) {
      setSelectGood({});
    }

    if(goods && goods.goods){
    setGoodsCat(goods.goods);
    }
  }, [goods])

  function handleChange(value) {
      console.log(`selected ${value}`);
     
      const good = goodsCat.filter((good) => good._id === value); 
      setSelectGood(...good);
      setId(value);
    }

    function changeGoodInSer (name, description, price, imgId) {
      console.log("----", typeof name, typeof description, typeof price, typeof imgId )
      changeGood(_id, name, description,price, imgId);
    }


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

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

const mapDispatchToProps = {
  changeGood : actionChangeOneGood,
}


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

export default CartChangeGood;