import React, { useCallback } from 'react';
import { PageErrorLoad } from '../../../PageListingError/web';
import { PageListingNotFound } from '../../../PageListingNotFound/web';
import { Pagination } from '../../../Pagination';
import { IPageListingChildrenProps } from '../PageListing.interface';
import { CardsListingContainerStyle } from './CardsListingContainer.style';

export function CardsListingContainer(props: IPageListingChildrenProps): JSX.Element {
   const { renderResource, renderResourceSkeleton, viewList } = props;
   const {
      resourcesTotal,
      skeletonResources,
      setPage,
      filters,
      starting,
      searching,
      resources,
      reloadPage,
      errorLoadData,
      limit,
   } = viewList;

   const changePage = useCallback((page) => {
      setPage(page);
   }, []);

   const currentPage = (filters.offset ?? 0) / limit + 1;

   const showCards = !starting && !searching && resources;
   const showCardsSkeleton = (starting || searching) && skeletonResources;
   const showPageError = errorLoadData;

   return (
      <CardsListingContainerStyle>
         {showPageError && (
            <span data-testid="error-page-listing">
               <PageErrorLoad retry={reloadPage} />
            </span>
         )}

         <div className="cards-listing">
            {showCards &&
               resources.map((resource, i) => (
                  <span key={`card-${resource.id}`} data-testid={`card-${resource.id}`}>
                     {renderResource(resource, i)}
                  </span>
               ))}
         </div>
         <div className="cards-listing cards-listing-skeleton">
            {showCardsSkeleton &&
               skeletonResources.map((resource, i) => (
                  <span key={`card-skeleton-${i}`} data-testid="skeleton-card">
                     {renderResourceSkeleton(resource, i)}
                  </span>
               ))}
         </div>
         {showCards && resources.length === 0 && (
            <span data-testid="not-found-page">
               <PageListingNotFound />
            </span>
         )}

         <div className="pagination-listing">
            <Pagination total={resourcesTotal} perPage={20} currentPage={currentPage} changePage={changePage} />
         </div>
      </CardsListingContainerStyle>
   );
}
