import { Button, Container, Grid } from '@mui/material';
import { Box } from '@mui/system';
import Image from 'next/image';
import { useMemo, useState } from 'react';
import { useFetchProductsByCategory } from '../../hooks/useFetchProductData';
import { compare } from '../../utils/helpers/sortHelpers';
import ProductCard from '../product-card/ProductCard';

const ProductsGrid = ({
  allProducts,
  hasNextPage,
  productType,
  fetchNextPage,
  sort,
}) => {
  const productsPerPage = 9;
  const [next, setNext] = useState(productsPerPage);

  const { data: filteredData } = useFetchProductsByCategory(productType);

  const allItems = useMemo(
    () => allProducts?.pages?.flatMap((page) => page.product),
    [allProducts]
  );

  const dataToDisplay =
    productType === 'All' || productType === ''
      ? allItems.sort(compare('name', sort)).map((item) => (
          <Grid key={item._id} item md={4} sm={6} xs={12} sx={{ mb: '100px' }}>
            <ProductCard product={item} />
          </Grid>
        ))
      : filteredData?.productsByCategory
          .slice(0, next)
          .sort(compare('name', sort))
          .map((item) => (
            <Grid
              key={item._id}
              item
              md={4}
              sm={6}
              xs={12}
              sx={{ mb: '100px' }}
            >
              <ProductCard product={item} />
            </Grid>
          ));

  const handleMoreProducts = () => {
    setNext(next + productsPerPage);
  };

  return (
    <Container
      sx={{
        mt: 10,
      }}
    >
      <Grid container spacing={2}>
        {dataToDisplay}
      </Grid>
      <Box textAlign="center" mt={-5} mb={5}>
        {hasNextPage && (productType === 'All' || productType === '') && (
          <Button
            onClick={fetchNextPage}
            startIcon={
              <Image
                src="/images/arrow.svg"
                alt="arrow down"
                width={29}
                height={29}
              />
            }
            sx={{
              backgroundColor: 'primary.main',
              height: 50,
              width: 150,
              color: 'white',
              ':hover': {
                bgcolor: 'primary.main', // theme.palette.primary.main
                color: 'white',
              },
            }}
          >
            Load More
          </Button>
        )}

        {filteredData && next < filteredData.productsByCategory.length && (
          <Button
            onClick={handleMoreProducts}
            startIcon={
              <Image
                src="/images/arrow.svg"
                alt="arrow down"
                width={29}
                height={29}
              />
            }
            sx={{
              backgroundColor: 'primary.main',
              height: 50,
              width: 150,
              color: 'white',
              ':hover': {
                bgcolor: 'primary.main', // theme.palette.primary.main
                color: 'white',
              },
            }}
          >
            Load More
          </Button>
        )}
      </Box>
    </Container>
  );
};

export default ProductsGrid;
