import { useParams } from 'react-router-dom';
import { useQuery, gql } from '@apollo/client';
import { member } from 'components/alliance/schema/fragments';

import {
  AllianceEventLogQuery,
  AllianceEventLogQueryVariables,
} from 'types/graphql';

import { Spinner } from 'components/common';
import { ErrorBoundary } from 'components/ErrorBoundary';

import { ActivityList } from './ActivityList';

export const ALLIANCE_EVENT_LOG = gql`
  query ALLIANCE_EVENT_LOG($allianceId: ID, $offset: Int, $limit: Int) {
    eventLog(allianceId: $allianceId, offset: $offset, limit: $limit) {
      items {
        id
        timestamp: timeStamp
        type: eventType
        text: eventDesc
        user: member {
          ...member
        }
        collectionId
      }
      offset
      length
    }
  }
  ${member}
`;

export const ActivityLog = ({ limit = 20 }: { limit?: number }) => {
  const { allianceId } = useParams();
  const { data, loading, fetchMore } = useQuery<
    AllianceEventLogQuery,
    AllianceEventLogQueryVariables
  >(ALLIANCE_EVENT_LOG, {
    variables: { allianceId, limit, offset: 0 },
    notifyOnNetworkStatusChange: true,
    nextFetchPolicy: 'cache-first',
  });

  const loadMore = async () => {
    try {
      await fetchMore({
        variables: {
          offset: data!.eventLog.offset + limit,
          // offset: data?.eventLog?.items?.length,
          limit,
        },
      });
    } catch (err) {
      console.error(err);
    }
  };

  return (
    <ErrorBoundary>
      <div className="padding4 spacingY4">
        <ActivityList data={data?.eventLog.items} />
        {data && data.eventLog.items.length < data.eventLog.length ? (
          <div className="link fz14" onClick={loadMore}>
            {loading ? 'Loading...' : 'Load more'}
          </div>
        ) : null}
        <Spinner show={loading} />
      </div>
    </ErrorBoundary>
  );
};
