import {useState, useEffect} from 'react';
import { Box, Typography, Button } from '@mui/material';
import { useSelector } from 'react-redux';

import Grid from '@mui/material/Grid2';

const ProductSuggestion = () => {

  const [suggestProducts, setSuggestProducts] = useState([]);
  const products = useSelector((state) => state.products.productsHistory.data);

  useEffect(() => {
    if (products && products.length > 0) {
      const getRandomProducts = (arr, num) => {
        const shuffled = [...arr].sort(() => 0.5 - Math.random());
        return shuffled.slice(0, num);
      };

      const randomProducts = getRandomProducts(products, 4); // Select 4 random elements
      setSuggestProducts(randomProducts);
    }
  }, [products]);

  const renderProduct = (id, img_url, title, price, currency) => {
    return (
      <Grid item size={{ xs: 12, 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: '4 / 4',
              objectPosition:"top center",
              objectFit: 'cover',
            }}
          />

          <Box sx={{ py: 5 }}>
            <Typography variant="h5" sx={{ fontWeight: "bolder" }}>
              {title}
            </Typography>
            <Typography variant="h6" >
              {`${currency} ${parseFloat(price).toFixed(2)}`}
            </Typography>
          </Box>
        </Box>
      </Grid>
    )
  }


  return (
    <Box sx={{ mb: 5 }}>
      <Grid container spacing={1} columns={12}>
        {suggestProducts.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

          // ID
          const parts = id.split('/');
          let prodID = parts[parts.length - 1];

          return renderProduct(prodID, img_url, title, price, currency)
        })}
      </Grid>
    </Box>
  );
};

export default ProductSuggestion;
