import { useState, useEffect } from 'react';
import { Box, Typography, IconButton, Pagination, Button } from '@mui/material';
import { useSelector, useDispatch } from 'react-redux';
import defaultImage from "../../assets/images/default.png"

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

const ProductHistoryList = () => {

  const products = useSelector((state) => state.products.products.data); // only used as referenced
  const [filterProducts, setFilterProducts] = useState([])

  useEffect(() => {

    if (products.length > 0 && localStorage.getItem('amber-product-history')) {

      const productHandleList = JSON.parse(localStorage.getItem('amber-product-history')) || []
      const selectedProducts = products.filter(({ handle }) => productHandleList.includes(handle)) || []

      setFilterProducts(selectedProducts)

    }

  }, [products])

  const renderProduct = (
    handle,
    img_url,
    title,
    collection_name,
    minPrice,
    minPriceCurrency,
    maxPrice,
    maxPriceCurrency,
    minDiscountPrice,
    minDiscountPriceCurrency,
    maxDiscountPrice,
    maxDiscountPriceCurrency,
    extra_desc,
    selected = false
  ) => {

    return (
      <Grid className="animate__animated animate__fadeIn" item size={{ xs: 6, sm: 6, md: 3 }}>

        <a href={`/products/${handle}`} style={{ textDecoration: "none", color: "#000" }}>
          <Box
            sx={{
              overflow: 'hidden',
              position: 'relative',
              cursor: 'pointer'
            }}

          >
            <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",
                  },
                  textDecoration: (minDiscountPrice > 0) ? "line-through" : "none"
                }}
              >
                {`${minPriceCurrency} ${parseFloat(minPrice).toFixed(2)}`}
              </Typography>

              {(minDiscountPrice > 0) && <Typography
                variant="body2"
                sx={{
                  fontWeight: "100",
                  fontSize: {
                    xs: "0.73rem",
                    sm: "0.73rem",
                    md: "0.875rem",
                  },
                }}
              >
                {`${minDiscountPriceCurrency} ${parseFloat(minDiscountPrice).toFixed(2)}`}
              </Typography>}
            </Box>
          </Box>
        </a>
      </Grid>
    )

  }


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

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

          let minPrice = minVariantPrice.amount
          let minPriceCurrency = minVariantPrice.currencyCode
          let maxPrice = maxVariantPrice.amount
          let maxPriceCurrency = maxVariantPrice.currencyCode
          // SHOULD BE THE DISCOUNTED PRICE
          let minDiscountPrice = compareAtPriceRangeMinVariantPrice.amount;
          let minDiscountPriceCurrency = compareAtPriceRangeMinVariantPrice.currencyCode;
          let maxDiscountPrice = compareAtPriceRangeMaxVariantPrice.amount;
          let maxDiscountPriceCurrency = compareAtPriceRangeMaxVariantPrice.currencyCode;

          let img_url = images[0]?.url || defaultImage
          let collection_name = collections[0]?.title

          if (index < 4) {
            return renderProduct(
              handle,
              img_url,
              title,
              collection_name,
              minPrice,
              minPriceCurrency,
              maxPrice,
              maxPriceCurrency,
              minDiscountPrice,
              minDiscountPriceCurrency,
              maxDiscountPrice,
              maxDiscountPriceCurrency,
              "",
              selected
            );
          }

        })}
      </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;
