import { useLazyQuery } from "@apollo/client";
import { List, Spin } from "antd";
import React, { useState } from "react";
import InfiniteScroll from "react-infinite-scroller";
import { SEARCH_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";
import JobsSearchFieldsMolecule from "../../molecules/jobs-search-fields/jobs-search-fields.molecule";

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

  const [callSearch, { loading, error, data, fetchMore }] = useLazyQuery(
    SEARCH_JOBS_PAGINATED,
    {
      variables: {
        offset: 0,
        limit: limit,
      },
    }
  );

  const handleSearch = (options) => {
    setState({ hasMore: true });
    callSearch(options);
  };

  const handleInfiniteOnLoad = async (page) => {
    if (fetchMore && data?.search_jobs) {
      // ipcRenderer.send(ipcTypes.app.toMain.track, {
      //   event: "FETCH_MORE_JOBS",
      // });
      await fetchMore({
        variables: {
          offset: limit * page,
        },
        updateQuery: (prev, { fetchMoreResult }) => {
          const previousJobs = prev?.search_jobs || [];
          const incomingJobs = fetchMoreResult?.search_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, {
            search_jobs: [...previousJobs, ...incomingJobs],
            search_jobs_aggregate: fetchMoreResult.search_jobs_aggregate || prev?.search_jobs_aggregate
          });

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

          return newCache;
        },
      });
    }
  };

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

  return (
    <div className="jobs-list-container">
      <JobsSearchFieldsMolecule callSearchQuery={handleSearch} />
      <div className="jobs-list-infinite-container">
        <InfiniteScroll
          pageStart={0}
          loadMore={handleInfiniteOnLoad}
          hasMore={!loading && state.hasMore}
          useWindow={false}
          threshold={30}
        >
          <List
            bordered
            dataSource={data ? data.search_jobs : []}
            renderItem={(item) => <JobsListItemMolecule item={item} />}
          >
            {loading && state.hasMore && (
              <div>
                <Spin />
              </div>
            )}
          </List>
        </InfiniteScroll>
      </div>
    </div>
  );
}
