import React, { useEffect } from 'react';
import { Box, Typography, Button } from '@mui/material';
import Grid from '@mui/material/Grid2';

//REDUX
import { useSelector, useDispatch } from 'react-redux';
import { fetchProducts } from '../../redux/slices/productSlice';

const ProductList = ({ size = 99999 }) => {

  const products = useSelector((state) => state.products.products.data)
  const dispatch = useDispatch();

  useEffect(() => {

    dispatch(fetchProducts())

  }, [])

  useEffect(() => {
    if(products) console.log(products)
  }, [products])

  const renderProduct = (id, img_url, title, collection, price, currency, extra_desc) => {

    return (
      <Grid item size={{ xs: 6, sm: 6, md: 3 }}>
        <Box
          onClick={() => { window.location.href = `/products/${id}` }}
          sx={{
            overflow: 'hidden',
            position: 'relative',
            cursor: 'pointer'
          }}

        >
          <img
            src={img_url}
            alt={title}
            style={{
              width: '100%',
              aspectRatio: '3 / 4',
              objectFit: 'cover',
            }}
          />

          {/* <Button sx={{ position: "absolute", top: 20, left: 20, boxShadow: 0 }} variant="contained">
            NEW
          </Button> */}

          <Box sx={{ py: 5 }}>
            <Typography variant="body2" >
              {collection}
            </Typography>
            <Typography variant="h5" sx={{ fontWeight: "bolder" }}>
              {title}
            </Typography>
            <Typography variant="body" >
              {`${currency} ${price}`}
            </Typography>
            <Typography variant="body2" sx={{ mt: 2 }}>
              {extra_desc}
            </Typography>
          </Box>
        </Box>
      </Grid>
    )

  }

  return (
    <Box sx={{ mb: 5 }}>
      <Grid container spacing={1} columns={12}>
        {products.map((product, index) => {
          
          let {id, title, compareAtPriceRange, images, collections} = product
          let price = compareAtPriceRange.maxVariantPrice.amount
          let currency = compareAtPriceRange.maxVariantPrice.currencyCode
          let img_url = images.nodes[0].url
          let collection_name = collections.nodes[0]?.title
          
          // ID
          const parts = id.split('/');
          let prodID = parts[parts.length - 1];


          if (index < size) {
            return renderProduct(prodID, img_url, title, collection_name, price, currency, "" )
          }

        })}
      </Grid>
    </Box>
  );
};

export default ProductList;
