import { useEffect, useState } from 'react';
import { Box, Typography, Button, FormControl, Select, MenuItem, InputBase } from '@mui/material';
import Grid from '@mui/material/Grid2';
import { styled } from "@mui/material";
//REDUX
import { useSelector, useDispatch } from 'react-redux';
import { fetchProducts, fetchProductsByCollection } from '../../redux/slices/productSlice';
//UTIL FUNCTION
function getAllTags(data) {
const products = data || [];
const allTags = products.flatMap(product => product.tags);
const uniqueTags = [...new Set(allTags)];
return uniqueTags;
}
const BootstrapInput = styled(InputBase)(({ theme }) => ({
'label + &': {
marginTop: theme.spacing(3),
},
'& .MuiInputBase-input': {
position: 'relative',
backgroundColor: "#2E2E2E",
border: '1px solid #ced4da',
color: "#FFF",
fontSize: 13,
padding: '5px 0',
paddingRight: '50px !important',
paddingLeft: "10px",
transition: theme.transitions.create(['border-color', 'box-shadow']),
'&:focus': {
borderRadius: 4,
borderColor: '#80bdff',
boxShadow: '0 0 0 0.2rem rgba(0,123,255,.25)',
},
},
'& .MuiSvgIcon-root': {
color: "#FFF !important"
},
}));
const ProductList = ({ size = 99999 }) => {
const products = useSelector((state) => state.products.products.data) // only used as referenced
const [filteredProducts, setFilteredProducts] = useState([]) // this one is the actual data to be rendered
const [categoryFilterOption, setCategoryFilterOption] = useState([])
const dispatch = useDispatch();
//filter
const [category, setCategory] = useState('all');
const [sort, setSort] = useState('all')
useEffect(() => {
// if user come from select collection
if (sessionStorage.getItem('amber-select-collection')) {
let { id } = JSON.parse(sessionStorage.getItem('amber-select-collection'))
dispatch(fetchProductsByCollection({ collectionId: id }))
} else if (sessionStorage.getItem('amber-select-category')) {
}
}, [])
useEffect(() => {
let productType = sessionStorage.getItem('amber-select-product-type')
let newFilteredProducts = products.filter(
(product) => product.productType === productType
);
const categoryList = getAllTags(newFilteredProducts) // yes we use tags as category, while I was coding this, this is the only way to implement category
setFilteredProducts(newFilteredProducts)
setCategoryFilterOption(categoryList)
}, [products])
useEffect(() => {
if (products?.length > 0) {
let productType = sessionStorage.getItem('amber-select-product-type')
let newFilteredProducts = products.filter(
(product) => {
if(category == 'all'){
return product.productType === productType
} else {
return product.productType === productType && product.tags.includes(category)
}
}
);
setFilteredProducts(newFilteredProducts)
}
}, [category])
useEffect(() => {
if (products) console.log(products)
}, [products])
const handleChange = (event) => {
//setInput({ ...input, [event.target.name]: event.target.value });
};
const renderProduct = (id, img_url, title, collection, price, currency, extra_desc) => {
return (
{ window.location.href = `/products/${id}` }}
sx={{
overflow: 'hidden',
position: 'relative',
cursor: 'pointer'
}}
>
{/* */}
{collection}
{title}
{`${currency} ${parseFloat(price).toFixed(2)}`}
{extra_desc}
)
}
return (
<>
{/* FILTER */}
{/* Left Side: Page Title */}
{`${filteredProducts.length} Item`}
{/* Right Side: Option Inputs */}
Filter By Category
Sort By
}
name="sort"
>
{/* LIST */}
{filteredProducts.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, "")
}
})}
>
);
};
export default ProductList;