import { useState, useEffect } from 'react';
import { Box, Typography, Button } from '@mui/material';
import { useSelector } from 'react-redux';
import Grid from '@mui/material/Grid2';
import { useNavigate } from "react-router-dom";

const ProductSuggestion = () => {

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

  const navigate = useNavigate();

  useEffect(() => {
    if (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 = (
    handle,
    img_url,
    title,
    collection_name,
    minPrice,
    minPriceCurrency,
    maxPrice,
    maxPriceCurrency,
    extra_desc,
    selected = false
  ) => {
    return (
      <Grid
        className="animate__animated animate__fadeIn"
        item
        size={{ xs: 6, sm: 6, md: 3 }}
      >
        <Box
          sx={{
            overflow: "hidden",
            position: "relative",
            cursor: "pointer",
          }}
          onClick={() => {
            navigate(`/products/${handle}`)
          }}
        >
          <img
            src={img_url}
            alt={title}
            style={{
              width: "100%",
              aspectRatio: "3 / 4",
              objectFit: "cover",
              objectPosition: "top center",
            }}
          />

          {selected && (
            <Button
              sx={{
                position: "absolute",
                top: {
                  xs: 0,
                  sm: 0,
                  md: 10,
                  lg: 20,
                },
                left: {
                  xs: 0,
                  sm: 0,
                  md: 10,
                  lg: 20,
                },
                boxShadow: 0,
                fontSize: 10,
              }}
              variant="contained"
            >
              NEW
            </Button>
          )}

          <Box sx={{ pb: 3, pt: 1, width: "90%" }}>
            <Typography
              variant="body2"
              sx={{
                fontWeight: "100",
                fontSize: {
                  xs: "0.65rem",
                  sm: "0.65rem",
                  md: "0.75rem",
                },
              }}
            >
              {collection_name}
            </Typography>
            <Typography
              variant="body2"
              sx={{
                fontWeight: "400",
                fontSize: {
                  xs: "0.73rem",
                  sm: "0.73rem",
                  md: "0.875rem",
                },
              }}
            >
              {title}
            </Typography>
            <Typography
              variant="body2"
              sx={{
                fontWeight: "100",
                fontSize: {
                  xs: "0.73rem",
                  sm: "0.73rem",
                  md: "0.875rem",
                },
              }}
            >
              {`${minPriceCurrency} ${parseFloat(minPrice).toFixed(2)}`}
            </Typography>
          </Box>
        </Box>
      </Grid>
    );
  };


  return (
    <Box sx={{ mb: 5 }}>
      <Grid container spacing={1} columns={12}>
        {suggestProducts.map((product, index) => {

          let {
            handle,
            title,
            images,
            collections,
            minVariantPrice,
            maxVariantPrice,
            productType,
            variants,
            selected,
          } = product;

          let minPrice = minVariantPrice.amount;
          let minPriceCurrency = minVariantPrice.currencyCode;
          let maxPrice = maxVariantPrice.amount;
          let maxPriceCurrency = maxVariantPrice.currencyCode;
          let img_url = images[0]?.url;
          let collection_name = collections[0]?.title;

          return renderProduct(
            handle,
            img_url,
            title,
            collection_name,
            minPrice,
            minPriceCurrency,
            maxPrice,
            maxPriceCurrency,
            "",
            selected
          );
        })}
      </Grid>
    </Box>
  );
};

export default ProductSuggestion;
