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,
      setPage,
      showCardsSkeleton,
      showCards,
      errorLoadData,
      reloadPage,
   } = useContext(PageListingContext);

   return (
      <>
         <CardListingContainerComponent
            resources={resources}
            renderResource={props.renderResource}
            resourcesTotal={resourcesTotal}
            currentPage={currentPage}
            skeletonResources={skeletonResources}
            renderResourceSkeleton={props.renderResourceSkeleton}
            changePage={setPage}
            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 className="cards-listing">
         {errorLoadData && <PageError retry={reloadPage} fullscreen />}

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

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

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

function EmptyComponent(props: any): any {
   return props.children;
}
