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 AlertComponent from "../../components/alert/alert.component";
import BillDetailEditContainer from "../../components/bill-detail-edit/bill-detail-edit.container";
import RbacWrapper from "../../components/rbac-wrapper/rbac-wrapper.component";
import { QUERY_ALL_BILLS_PAGINATED } from "../../graphql/bills.queries";
import {
  setBreadcrumbs,
  setSelectedHeader,
} from "../../redux/application/application.actions";
import BillsPageComponent from "./bills.page.component";

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

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

  useEffect(() => {
    document.title = t("titles.bills-list");
    setSelectedHeader("bills");
    setBreadcrumbs([
      { link: "/manage/bills", label: t("titles.bc.bills-list") },
    ]);
  }, [t, setBreadcrumbs, setSelectedHeader]);

  const { loading, error, data, refetch } = useQuery(
    QUERY_ALL_BILLS_PAGINATED,
    {
      fetchPolicy: "network-only",
      nextFetchPolicy: "network-only",
      variables: {
        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 message={error.message} type="error" />;
  return (
    <RbacWrapper action="bills:list">
      <div>
        <BillsPageComponent
          data={data ? data.bills : []}
          loading={loading}
          refetch={refetch}
          total={data ? data.bills_aggregate.aggregate.count : 0}
        />

        <BillDetailEditContainer />
      </div>
    </RbacWrapper>
  );
}
export default connect(null, mapDispatchToProps)(BillsPageContainer);
