import { useQuery } from "@apollo/client";
import { Button, List } from "antd";
import React, { useState } from "react";
import InfiniteScroll from "react-infinite-scroller";
import { QUERY_ALL_JOBS_PAGINATED } from "../../../graphql/jobs.queries";
import ErrorResultAtom from "../../atoms/error-result/error-result.atom";
import JobsListItemMolecule from "../../molecules/jobs-list-item/jobs-list-item.molecule";

const limit = 20;
export default function JobsTableOrganism() {
  const [state, setState] = useState({ hasMore: true });

  const { loading, error, data, refetch, fetchMore } = useQuery(QUERY_ALL_JOBS_PAGINATED, {
    variables: {
      offset: 0,
      limit: limit,
      order: [{ updated_at: "desc" }]
    }
  });

  const handleInfiniteOnLoad = async (page) => {
    console.log("Fetching more records!", page, fetchMore);
    if (fetchMore) {
      await fetchMore({
        variables: {
          offset: limit * page
        },

        updateQuery: (prev, { fetchMoreResult }) => {
          const previousJobs = prev?.jobs || [];
          const incomingJobs = fetchMoreResult?.jobs || [];

          if (!incomingJobs.length) {
            console.log("No more results. Fetch More was empty.");
            setState((current) => ({ ...current, hasMore: false }));
            return prev;
          }

          const newCache = Object.assign({}, prev, {
            jobs: [...previousJobs, ...incomingJobs],
            jobs_aggregate: fetchMoreResult.jobs_aggregate || prev?.jobs_aggregate
          });

          if (newCache.jobs.length >= (data && data.jobs_aggregate.aggregate.count)) {
            console.log("No more results.");
            setState((current) => ({ ...current, hasMore: false }));
          }

          return newCache;
        }
      });
      // if (data.jobs.length >= data.jobs_aggregate.aggregate.count) {
      //   console.log("No more results.");
      //   setState({ ...state, hasMore: false });
      // }
    }
  };

  if (error) return <ErrorResultAtom title="Error fetching Jobs data." errorMessage={JSON.stringify(error)} />;

  return (
    <div className="jobs-list-container">
      <Button
        onClick={() => {
          setState({ hasMore: true });
          refetch();
        }}
        style={{ marginBottom: ".5rem" }}
        size="large"
      >
        Refresh
      </Button>
      <div className="jobs-list-infinite-container">
        <InfiniteScroll
          pageStart={0}
          loadMore={handleInfiniteOnLoad}
          hasMore={!loading && state.hasMore}
          useWindow={false}
          threshold={30}
        >
          <List
            bordered
            loading={loading}
            dataSource={
              data
                ? [
                    //{ isRefresh: true },
                    ...data.jobs
                  ]
                : []
            }
            renderItem={(item) => <JobsListItemMolecule item={item} refetch={refetch} />}
          ></List>
        </InfiniteScroll>
      </div>
      <div>
        {`${data ? data.jobs.length : 0} jobs loaded. ${data ? data.jobs_aggregate.aggregate.count : 0} total jobs.`}
      </div>
    </div>
  );
}
