import { useQuery } from "@apollo/client/react";
import queryString from "query-string";
import { connect } from "react-redux";
import { useLocation } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { QUERY_ALL_TT_APPROVALS_PAGINATED } from "../../graphql/tt-approvals.queries";
import AlertComponent from "../alert/alert.component";
import TtApprovalsListComponent from "./tt-approvals-list.component";

const mapStateToProps = createStructuredSelector({});

const mapDispatchToProps = () => ({});

export function TimeTicketsContainer() {
  const searchParams = queryString.parse(useLocation().search);
  const { page, sortcolumn, sortorder, search, searchObj } = searchParams;

  const { loading, error, data, refetch } = useQuery(QUERY_ALL_TT_APPROVALS_PAGINATED, {
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only",
    variables: {
      search: search || "",
      offset: page ? (page - 1) * 25 : 0,
      limit: 25,
      order: [
        searchObj
          ? JSON.parse(searchObj)
          : {
              [sortcolumn || "date"]: sortorder ? (sortorder === "descend" ? "desc" : "asc") : "desc"
            }
      ]
    }
  });

  if (error) return <AlertComponent title={error.message} type="error" />;

  return (
    <TtApprovalsListComponent
      loading={loading}
      tt_approval_queue={data ? data.tt_approval_queue : []}
      total={data ? data.tt_approval_queue_aggregate.aggregate.count : 0}
      refetch={refetch}
    />
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(TimeTicketsContainer);
