import { parseAsInteger, useQueryState } from 'nuqs';
import Stack from '@material-hu/mui/Stack';

import Pagination from '@material-hu/components/design-system/Inputs/Pagination';

import { useGetProducts } from '../../hooks/useGetProducts';
import { ProductListItem } from '../components/ProductListItem';
import { ProductListSkeleton } from '../components/ProductListSkeleton';

import { CatalogStateCard } from './components/CatalogStateCard';

const CATALOG_LIMIT = 10;

export const Catalog = () => {
  const [page, setPage] = useQueryState('page', parseAsInteger.withDefault(1));

  const {
    products,
    totalPages,
    isLoading,
    isSuccess,
    isPreviousData,
    state,
    refetch,
  } = useGetProducts({ page, limit: CATALOG_LIMIT });

  const handleRetry = () => refetch();

  const showList = isSuccess && !isLoading;

  return (
    <Stack sx={{ gap: 2 }}>
      {isLoading && <ProductListSkeleton />}
      {showList && (
        <>
          <Stack sx={{ gap: 2, opacity: isPreviousData ? 0.5 : 1 }}>
            {products.map(product => (
              <ProductListItem
                key={product.id}
                product={product}
              />
            ))}
          </Stack>
          {totalPages > 1 && (
            <Pagination
              type="basic"
              page={page}
              totalPages={totalPages}
              loading={isPreviousData}
              onChangePage={setPage}
            />
          )}
        </>
      )}
      <CatalogStateCard
        state={state}
        onRetry={handleRetry}
      />
    </Stack>
  );
};
