import { Card, Image, Button, Alert, Row } from 'antd';
import { connect } from 'react-redux';
import { backURL } from '../api';
import { actionCartAdd } from '../action';
import { useHistory } from 'react-router-dom';

const ContentSearch = ({ value, onAdd }) => {
  console.log('value', value);
  const history = useHistory();

  const onClose = (e) => {
    console.log(e, 'I was closed.');
    history.push('/');
  };

  return (
    <> { value.length
      ? <Row >
      {value.map((item) =>
      <Card key={item._id} title={item.name} style={{ width: 350 }} hoverable>
          {item.images &&
          item.images[0] &&
          item.images[0].url &&
          <Image width={300} src={backURL + '/' + item.images[0].url} />}
          <p>{item.description}</p>
          <p>{item.price} грн</p>
          <Button onClick={() => onAdd({
            _id: item._id,
            name: item.name,
            price: item.price,
            images: item.images
          })}>Купить</Button>
        </Card>)}
        </Row>
      : <>
         <Alert
            message="Товара с таким названием не существует"
            type="error"
            closable
            onClose={onClose}
          />
        </>
        }
    </>
  );
};

const mapStateToProps = (state) => ({
  value: state.promise.searchGood?.payload || []
});
const mapDispatchToProps = {
  onAdd: actionCartAdd
};

const GoodSearch = connect(mapStateToProps, mapDispatchToProps)(ContentSearch);

export default GoodSearch;
