import { useQuery } from "@apollo/client/react";
import queryString from "query-string";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useLocation, useNavigate } 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";
import useLocalStorage from "../../utils/useLocalStorage";
import { pageLimit } from "../../utils/config";
import FeatureWrapperComponent from "../../components/feature-wrapper/feature-wrapper.component";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import { Card } from "antd";
import UpsellComponent, { upsellEnum } from "../../components/upsell/upsell.component";

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

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

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

  // Persisted table state (sorting & filtering)
  const [persistState, setPersistState] = useLocalStorage("bills_list_sort", {
    sortedInfo: {},
    filteredInfo: { vendorname: [] }
  });

  const { loading, error, data, refetch } = useQuery(QUERY_ALL_BILLS_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"
            }
      ],
      where: searchParams.vendorIds ? { vendorid: { _in: searchParams.vendorIds.split(",") } } : undefined
    }
  });

  const handleTableChange = (pagination, filters, sorter) => {
    const search = queryString.parse(location.search);

    const vendorArr = filters?.vendorname ?? [];
    const newVendorIds = vendorArr.length ? vendorArr.join(",") : undefined;
    const vendorFilterChanged = search.vendorIds !== newVendorIds;

    search.page = vendorFilterChanged || !search.page ? 1 : pagination.current;
    newVendorIds ? (search.vendorIds = newVendorIds) : delete search.vendorIds;

    const { columnKey, order, column } = sorter || {};
    if (column?.sortObject) {
      search.searchObj = JSON.stringify(column.sortObject(order));
      delete search.sortcolumn;
      delete search.sortorder;
    } else {
      delete search.searchObj;
      search.sortcolumn = order ? columnKey : null;
      search.sortorder = order ?? null; // keep explicit null to mirror prior behavior
    }

    setPersistState({
      sortedInfo: sorter || {},
      filteredInfo: { vendorname: vendorArr }
    });

    history({ search: queryString.stringify(search) });
  };

  useEffect(() => {
    const search = queryString.parse(location.search);
    let changed = false;

    const vendorPersisted = persistState.filteredInfo.vendorname || [];
    if (!search.vendorIds && vendorPersisted.length) {
      search.vendorIds = vendorPersisted.join(",");
      search.page = 1; // reset page when injecting filter
      changed = true;
    }

    const { sortedInfo } = persistState;
    if (!search.searchObj && !search.sortcolumn && sortedInfo?.order) {
      const { columnKey, order } = sortedInfo;
      if (columnKey) {
        const dir = order === "descend" ? "desc" : "asc";
        if (columnKey === "vendorname") {
          search.searchObj = JSON.stringify({ vendor: { name: dir } });
        } else if (columnKey === "ro_number") {
          search.searchObj = JSON.stringify({ job: { ro_number: dir } });
        } else {
          search.sortcolumn = columnKey;
          search.sortorder = order;
        }
        changed = true;
      }
    }

    if (changed) {
      history({ search: queryString.stringify(search) });
      return;
    }

    const hasPersistSort = !!sortedInfo?.order;
    const hasUrlSort = !!(search.searchObj || (search.sortcolumn && search.sortorder));
    if (!hasPersistSort && hasUrlSort) {
      let derived = {};
      if (search.searchObj) {
        try {
          const o = JSON.parse(search.searchObj);
          if (o.vendor?.name) {
            derived = { columnKey: "vendorname", order: o.vendor.name === "desc" ? "descend" : "ascend" };
          } else if (o.job?.ro_number) {
            derived = { columnKey: "ro_number", order: o.job.ro_number === "desc" ? "descend" : "ascend" };
          }
        } catch {
          /* ignore parse errors */
        }
      } else {
        derived = { columnKey: search.sortcolumn, order: search.sortorder };
      }
      if (derived.order) setPersistState((prev) => ({ ...prev, sortedInfo: derived }));
    }
  }, [location.search]);

  if (error) return <AlertComponent title={error.message} type="error" />;
  return (
    <FeatureWrapperComponent
      featureName="bills"
      noauth={
        <Card>
          <UpsellComponent upsell={upsellEnum().bills.general} />
        </Card>
      }
    >
      <RbacWrapper action="bills:list">
        <div>
          <BillsPageComponent
            data={data ? data.bills : []}
            loading={loading}
            refetch={refetch}
            total={data ? data.bills_aggregate.aggregate.count : 0}
            handleTableChange={handleTableChange}
            sortedInfo={persistState.sortedInfo || {}}
          />

          <BillDetailEditContainer />
        </div>
      </RbacWrapper>
    </FeatureWrapperComponent>
  );
}

export default connect(null, mapDispatchToProps)(BillsPageContainer);
