import React, { useContext } from 'react';
import * as _ from 'lodash';
import { PageError } from '../../PageError';
import { PageListingNotFound } from '../../PageListingNotFound';
import { PageListingContext } from '../PageListingContext';
import { ICardContainerProps } from './CardListingContainer.interface';

export const CardListingContainer = function FiltersComponent(props: ICardContainerProps): JSX.Element {
   const {
      resources,
      skeletonResources,
      resourcesTotal,
      currentPage,
      changePage,
      showCardsSkeleton,
      showCards,
      errorLoadData,
      reloadPage,
   } = useContext(PageListingContext);

   return (
      <>
         <CardListingContainerComponent
            resources={resources}
            renderResource={props.renderResource}
            resourcesTotal={resourcesTotal}
            currentPage={currentPage}
            skeletonResources={skeletonResources}
            renderResourceSkeleton={props.renderResourceSkeleton}
            changePage={changePage}
            showCardsSkeleton={showCardsSkeleton}
            showCards={showCards}
            errorLoadData={errorLoadData}
            reloadPage={reloadPage}
         />
      </>
   );
};

const CardListingContainerComponent = React.memo(function FiltersDesktop(props: any): JSX.Element {
   const {
      showCards,
      showCardsSkeleton,
      errorLoadData,
      resources,
      renderResource,
      resourcesTotal,
      skeletonResources,
      renderResourceSkeleton,
      currentPage,
      changePage,
      reloadPage,
   } = props;

   return (
      <div>
         <div className="cards-listing">
            {errorLoadData && <PageError retry={reloadPage} fullscreen />}

            {showCards &&
               !!resourcesTotal &&
               resources.map((resource, i) => (
                  <span key={`card-${resource.id}`} data-testid={`card-${resource.id}`}>
                     {renderResource(resource, i)}
                  </span>
               ))}

            {showCards && !resourcesTotal && <PageListingNotFound />}

            <div className="cards-listing-skeleton">
               {showCardsSkeleton &&
                  skeletonResources.map((resource, i) => (
                     <span key={`card-skeleton-${i}`} data-testid="skeleton-card">
                        {renderResourceSkeleton(resource, i)}
                     </span>
                  ))}
            </div>
         </div>
      </div>
   );
}, _.isEqual);
