import React from 'react'
import MagicGrid from 'magic-grid-react'
import { withStyles } from '@material-ui/core/styles'
import PropTypes from 'prop-types'
import axios from 'axios'
import ProductThumb from './ProductThumb'
import ApiLink from './ApiLink'
import { Loader } from './Loader'


const styles = () => ({
  masonry: {
    columns: 5,
    textAlign: 'center',
    columnGap: 1,
  },
});

const MagicGridConfig = {
  animate: true,
  gutter: 10,
};

// eslint-disable-next-line max-len
const Item = (arr) => arr.products.map((pdt) => <ProductThumb pdt={pdt} key={pdt.id} cat_url={arr.cat_url} pdt_id={pdt.id} pdt_name={pdt.name} pdt_price={pdt.d_price} img={pdt.thumb} />);

class SubProductList extends React.Component {
  _isMounted = true

  state = {
    products: [],
  }
  

  


  componentDidMount() {
    this._isMounted = true;
   
    axios.get(ApiLink.sub_product_list_link + this.props.cat_id).then((r) => {
      if (r.data.length > 0) {
        if (this._isMounted) {
          this.setState({
            products: r.data,
          });
        }
      } else if (this._isMounted) {
        this.setState({
          products: null,
        });
      }
    });
  }

  componentWillUnmount() {
    this._isMounted = false;
  }


  render() {
    const state = this.state;
    if (state.products == null) {
      return <h4> No Product Found</h4>;
    } if (state.products.length > 0) {
      return (
        <MagicGrid {...MagicGridConfig}>
          <Item products={state.products} cat_url={this.props.cat_url} />
        </MagicGrid>
      );
    }
    return <Loader />
  }
}

SubProductList.propTypes = {
  classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(SubProductList);
