import { useSearch } from 'hooks/useSearch';
import { useSortingPopup, SortingConfig } from 'hooks/useSorting';

import { Box } from 'components/common';

import { CollectionsList } from './CollectionsList';
import { SearchResults } from './SearchResults';
import { AllianceQuery } from 'types/graphql';

const SEARCH_PARAMS = ['name'];

type AllianceCollections = AllianceQuery['alliance']['collections'];
type AllianceCollection = AllianceCollections['0'];

const SORTING_CONFIG: SortingConfig<AllianceCollection> = {
  options: [
    { label: 'Name', value: 'name', selector: (i) => i.name },
    {
      label: 'Date created',
      value: 'date',
      type: 'date',
      selector: (i) => i.dateCreated,
    },
    {
      label: 'Total profiles',
      value: 'number',
      type: 'number',
      selector: (i) => i.totalProfiles,
    },
  ],
  sortBy: 'date',
};

export const Collections = ({
  data = [],
  storageKey = 'CollectionsList',
}: {
  data?: AllianceCollections;
  storageKey?: string;
}) => {
  const { match, keyword, onSearch } = useSearch(SEARCH_PARAMS);

  const [sort, sortingFlyout] = useSortingPopup(SORTING_CONFIG, storageKey);

  return (
    <Box spacingY={4}>
      <Box display="flex" paddingX={4}>
        <div className="w100 flex alignCenter spacing2">
          <input
            className="search fz16 bold"
            type="search"
            placeholder="Filter"
            onChange={onSearch}
          />
        </div>
        <div className="w100 flex alignCenter justifyEnd">
          <span
            onClick={(ev) => sortingFlyout.toggle(ev.currentTarget)}
            className="fz16 bold c-gray cup"
            style={{ userSelect: 'none' }}
          >
            Sort
          </span>
        </div>
      </Box>
      {keyword ? (
        <SearchResults data={sort(data)} search={match(keyword)} />
      ) : (
        <CollectionsList items={sort(data)} />
      )}
    </Box>
  );
};
