import { Box } from '@mui/system';
import Head from 'next/head';
import { useState } from 'react';
import FilterSort from '../../components/filter-sort/FilterSort';
import Loader from '../../components/loader/Loader';
import ProductsGrid from '../../components/products-grid/ProductsGrid';
import ProductsHero from '../../components/products-hero/ProductsHero';
import { useInfiniteProducts } from '../../hooks/useInfiniteQuery';

const Products = () => {
  const [filter, setFilter] = useState('All');
  const [sort, setSort] = useState('asc');
  const { data, isLoading, fetchNextPage, hasNextPage } =
    useInfiniteProducts(filter);

  const handleProductTypeChange = (event) => {
    const filterText = event.target.value;
    setFilter(filterText);
  };

  const handleSortChange = (event) => {
    const sort = event.target.value;
    setSort(sort);
  };

  if (isLoading) {
    return <Loader loading={isLoading} />;
  }

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      <Head>
        <title>NextJS template</title>
        <meta name="description" content="Random data with pagination..." />
      </Head>
      <ProductsHero />
      <FilterSort
        handleProductTypeChange={handleProductTypeChange}
        productType={filter}
        sort={sort}
        handleSortChange={handleSortChange}
      />
      <ProductsGrid
        allProducts={data}
        sort={sort}
        productType={filter}
        fetchNextPage={fetchNextPage}
        hasNextPage={hasNextPage}
      />
    </Box>
  );
};

export default Products;
