import { Button, Dropdown } 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";
import InstanceRenderManager from "../../utils/instanceRenderMgr";

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

export function JobsCloseAutoAllocate({ bodyshop, joblines, form, disabled }) {
  const { t } = useTranslation();

  const handleAllocate = (defaults) => {
    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 (
          InstanceRenderManager({
            imex: !jl.part_type && !jl.mod_lbr_ty,
            rome: !ret.profitcenter_part,
          })
        ) {
          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 if (jl.act_price > 0) {
            ret.profitcenter_part = defaults.profits["PAO"];
          } else {
            ret.profitcenter_part = null;
          }
        }
        return ret;
      })
    });
  };

  const handleAutoAllocateClick = () => {
    logImEXEvent("jobs_close_allocate_auto");

    const { defaults } = bodyshop.md_responsibility_centers;
    handleAllocate(defaults);
  };

  const handleMenuClick = ({ item, key, keyPath, domEvent }) => {
    logImEXEvent("jobs_close_allocate_auto_dms");
    form.setFieldsValue({ dms_allocation: key });
    handleAllocate(bodyshop.md_responsibility_centers.dms_defaults.find((x) => x.name === key));
  };

  const menu =
    bodyshop.cdk_dealerid || bodyshop.pbs_serialnumber
      ? {
          items: bodyshop.md_responsibility_centers.dms_defaults.map((mapping) => ({
            key: mapping.name,
            label: mapping.name,
            disabled: disabled
          })),
          onClick: handleMenuClick
        }
      : {
          items: []
        };

  return bodyshop.cdk_dealerid || bodyshop.pbs_serialnumber ? (
    <Dropdown menu={menu}>
      <Button disabled={disabled}>{t("jobs.actions.dmsautoallocate")}</Button>
    </Dropdown>
  ) : (
    <Button onClick={handleAutoAllocateClick} disabled={disabled}>
      {t("jobs.actions.autoallocate")}
    </Button>
  );
}

export default connect(mapStateToProps, null)(JobsCloseAutoAllocate);
