import { Button } from "antd";
import _ from "lodash";
import React from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { selectBodyshop } from "../../redux/user/user.selectors";
const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
});

export function JobsCloseAutoAllocate({ bodyshop, joblines, form, disabled }) {
  const { t } = useTranslation();
  const handleAllocate = () => {
    logImEXEvent("jobs_close_allocate_auto");

    const { defaults } = bodyshop.md_responsibility_centers;

    form.setFieldsValue({
      joblines: joblines.map((jl) => {
        const ret = _.cloneDeep(jl);
        if (jl.part_type) {
          ret.profitcenter_part = defaults.profits[jl.part_type.toUpperCase()];
        } else {
        }
        if (jl.mod_lbr_ty) {
          ret.profitcenter_labor =
            defaults.profits[jl.mod_lbr_ty.toUpperCase()];
        } else {
          ret.profitcenter_labor = null;
        }
        //Verify that this is also manually updated in server/job-costing
        if (!jl.part_type && !jl.mod_lbr_ty) {
          const lineDesc = jl.line_desc ? jl.line_desc.toLowerCase() : "";
          if (lineDesc.includes("shop materials")) {
            ret.profitcenter_part = defaults.profits["MASH"];
          } else if (lineDesc.includes("paint/materials")) {
            ret.profitcenter_part = defaults.profits["MAPA"];
          } else if (lineDesc.includes("ats amount")) {
            ret.profitcenter_part = defaults.profits["ATS"];
          } else {
            ret.profitcenter_part = null;
          }
        }
        return ret;
      }),
    });
  };

  return (
    <Button onClick={handleAllocate} disabled={disabled}>
      {t("jobs.actions.autoallocate")}
    </Button>
  );
}
export default connect(mapStateToProps, null)(JobsCloseAutoAllocate);
