import { useState, useEffect } from 'react';
import { Box, Typography, IconButton, Pagination } from '@mui/material';
import { useSelector, useDispatch } from 'react-redux';
import { fetchProductsHistory } from '../../redux/slices/productSlice';

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

const ProductHistoryList = () => {

  const products = useSelector((state) => state.products.productsHistory.data) // state.store.initialState.data
  const dispatch = useDispatch()

  useEffect(() => {

    if (localStorage.getItem('amber-product-history')) {

      let productIDList = JSON.parse(localStorage.getItem('amber-product-history'))

      dispatch(fetchProductsHistory(productIDList))

    }

  }, [])

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

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

    return (
      <Grid item size={{ xs: 12, md: 2 }}>
        <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}>
        {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

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

            return renderProduct(prodID, img_url, title, price, currency)

        })}
      </Grid>
      {/* Pagination Controls - DON'T REMOVE, CAUSE IT IS STILL HAVEN'T BEEN DECIDED IF WE NEED TO HAVA PAGINATION OR NOT*/}
      {/* <Box
        sx={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          mt: 4,
        }}
      >
        <Pagination
          count={totalPages}
          page={currentPage}
          onChange={handleChangePage}
          sx={{ mx: 2 }}
        />
      </Box> */}
    </Box>
  );
};

export default ProductHistoryList;
