import React from 'react';
import { Form } from '@unform/web';
import { Select } from '../../../Select/web';
import { Button } from '../../../Button/web';
import { TagsFilters } from '../../../TagsFilters/web';
import { IPageListingChildrenProps } from '../PageListing.interface';
import { SubHeaderListingContainerStyle } from './SubHeaderListingContainer.style';

export function SubHeaderListingContainer(props: IPageListingChildrenProps): JSX.Element {
   const { tagsFilters, tagsFiltersRef, viewList } = props;
   const { filters } = viewList;

   return (
      <SubHeaderListingContainerStyle>
         <ResultsInfo {...props} />

         {tagsFilters && (
            <div className="tags-filter-container">
               <TagsFilters ref={tagsFiltersRef} {...tagsFilters} filters={filters} />
            </div>
         )}
      </SubHeaderListingContainerStyle>
   );
}

function ResultsInfo(props: IPageListingChildrenProps): JSX.Element {
   const { formSortRef, openFilters, sortOptions, showCountListing = true, viewList } = props;

   const { setSort, filters, resourcesTotal, searching, starting } = viewList;

   const page = filters.page ?? 1;
   let pageCountStart = (page - 1) * 20 + 1;
   pageCountStart = resourcesTotal ? pageCountStart : 0;
   let pageCountEnd = (page - 1) * 20 + 20;
   pageCountEnd = pageCountEnd > resourcesTotal ? resourcesTotal : pageCountEnd;

   return (
      <div className="results-info">
         <div className="text-results">
            {showCountListing && (
               <span className={`${(searching || starting) && 'text-skeleton'} text-non-skeleton`}>
                  <b>{pageCountStart}</b>-<b>{pageCountEnd}</b> de <b>{resourcesTotal}</b> resultados
               </span>
            )}
         </div>

         <div className="btn-filter-row">
            <Button className="btn-filter" onClick={openFilters} data-cy="open-mobile-filters" type="button">
               Editar Filtros
            </Button>
         </div>

         {sortOptions && (
            <div className="sort">
               <Form onSubmit={() => {}} initialData={filters} ref={formSortRef}>
                  <Select
                     name="sort"
                     onChange={(e) => setSort(e.target.value)}
                     data-cy="sort-filters"
                     options={sortOptions}
                  />
               </Form>
            </div>
         )}
      </div>
   );
}
