import { useQuery } from "@apollo/client";
import queryString from "query-string";
import React, { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useLocation } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import AlertComponent from "../../components/alert/alert.component";
import PaymentsListPaginated from "../../components/payments-list-paginated/payment-list-paginated.component";
import RbacWrapper from "../../components/rbac-wrapper/rbac-wrapper.component";
import { QUERY_ALL_PAYMENTS_PAGINATED } from "../../graphql/payments.queries";
import { setBreadcrumbs, setSelectedHeader } from "../../redux/application/application.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { pageLimit } from "../../utils/config";
import FeatureWrapperComponent from "../../components/feature-wrapper/feature-wrapper.component";
import InstanceRenderManager from "../../utils/instanceRenderMgr";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});

const mapDispatchToProps = (dispatch) => ({
  setBreadcrumbs: (breadcrumbs) => dispatch(setBreadcrumbs(breadcrumbs)),
  setSelectedHeader: (key) => dispatch(setSelectedHeader(key))
});

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

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

  useEffect(() => {
    document.title = t("titles.payments-all", {
      app: InstanceRenderManager({
        imex: "$t(titles.imexonline)",
        rome: "$t(titles.romeonline)"
      })
    });
    setSelectedHeader("allpayments");
    setBreadcrumbs([{ link: "/manage/payments", label: t("titles.bc.payments-all") }]);
  }, [t, setBreadcrumbs, setSelectedHeader]);

  if (error) return <AlertComponent message={error.message} type="error" />;
  return (
    <FeatureWrapperComponent featureName="payments">
      <RbacWrapper action="payments:list">
        <PaymentsListPaginated
          refetch={refetch}
          loading={loading}
          searchParams={searchParams}
          total={data ? data.payments_aggregate.aggregate.count : 0}
          payments={data ? data.payments : []}
        />
      </RbacWrapper>
    </FeatureWrapperComponent>
  );
}

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