import { Button, Dropdown, Menu } 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 = (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 (!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;
      }),
    });
  };

  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 overlay = (bodyshop.cdk_dealerid || bodyshop.pbs_serialnumber) && (
    <Menu onClick={handleMenuClick}>
      {bodyshop.md_responsibility_centers.dms_defaults.map((mapping) => (
        <Menu.Item disabled={disabled} key={mapping.name}>
          {mapping.name}
        </Menu.Item>
      ))}
    </Menu>
  );

  return bodyshop.cdk_dealerid || bodyshop.pbs_serialnumber ? (
    <Dropdown overlay={overlay}>
      <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);
