import { useQuery } from '@apollo/client';
import { ALL_ALLIANCES } from 'components/alliance/schema/queries';
import { AllAlliancesQuery } from 'types/graphql';

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

import { Box, Button, Spinner } from 'components/common';
import { Header } from 'components/Header';

import { CreateAllianceModal } from 'components/alliance/modals';
import { AlliancePageItem, AlliancePageItemProps } from './AlliancePageItem';

export const AllianceList = ({ items }: { items: AlliancePageItemProps[] }) => {
  return (
    <Box spacingY={2}>
      {items.length ? (
        items.map((item) => {
          return <AlliancePageItem {...item} key={item.id} />;
        })
      ) : (
        <div className="padding4">Nothing found</div>
      )}
    </Box>
  );
};

AllianceList.defaultProps = {
  items: [],
};

type AllianceItem = AllAlliancesQuery['allAlliances']['0'];

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

const SEARCH_PARAMS = ['name'];

export const AlliancesPage = () => {
  const { data, loading } = useQuery<AllAlliancesQuery>(ALL_ALLIANCES, {
    fetchPolicy: 'network-only',
    nextFetchPolicy: 'cache-first',
  });

  const { match, keyword, onSearch } = useSearch(SEARCH_PARAMS);

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

  const createAllianceModal = useModal(CreateAllianceModal);

  const hasData = data?.allAlliances?.length !== 0;

  return (
    <Box
      position="relative"
      display="flex"
      column
      overflow="autoY"
      style={{ height: '100%', paddingBottom: 100 }}
    >
      <Header
        className="sticky"
        style={{ top: 0, zIndex: 1 }}
        title="My Alliances"
        right={
          hasData && (
            <Box spacing={4}>
              <Button onClick={() => createAllianceModal.show()}>
                Create alliance
              </Button>
            </Box>
          )
        }
      />
      {!loading &&
        (hasData ? (
          <Box padding={4}>
            <Box display="flex" justify="between" padding={4}>
              <input
                className="search fz16 bold"
                type="search"
                placeholder="Filter"
                onChange={onSearch}
              />
              <span
                onClick={(ev) => sortingFlyout.toggle(ev.currentTarget)}
                className="fz16 bold c-gray cup"
                style={{ userSelect: 'none' }}
              >
                Sort
              </span>
            </Box>
            <AllianceList
              items={
                keyword
                  ? sort(data!.allAlliances).filter(match(keyword))
                  : sort(data!.allAlliances)
              }
            />
          </Box>
        ) : (
          <Box
            flex="grow"
            display="flex"
            align="center"
            justify="center"
            spacing={4}
          >
            <Button size="l" onClick={() => createAllianceModal.show()}>
              Create alliance
            </Button>
          </Box>
        ))}
      <Spinner show={loading} />
    </Box>
  );
};
