import { useTreatmentsWithConfig } from "@splitsoftware/splitio-react";
import { Form, Input, InputNumber, Modal, Select, Switch } from "antd";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import InputCurrency from "../form-items-formatted/currency-form-item.component";
import JoblinesPreset from "../job-lines-preset-button/job-lines-preset-button.component";
import LayoutFormRow from "../layout-form-row/layout-form-row.component";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(JobLinesUpsertModalComponent);

export function JobLinesUpsertModalComponent({ bodyshop, open, jobLine, handleCancel, handleFinish, loading }) {
  const { t } = useTranslation();
  const [form] = Form.useForm();

  useEffect(() => {
    form.resetFields();
  }, [open, form]);

  const {
    treatments: { Allow_Negative_Jobline_Price, Autohouse_Detail_line }
  } = useTreatmentsWithConfig({
    attributes: {},
    names: ["Allow_Negative_Jobline_Price", "Autohouse_Detail_line"],
    splitKey: bodyshop.imexshopid
  });

  return (
    <Modal
      title={jobLine?.id ? t("joblines.labels.edit") : t("joblines.labels.new")}
      forceRender
      open={open}
      width="60%"
      okText={t("general.actions.save")}
      onOk={() => form.submit()}
      okButtonProps={{ loading: loading }}
      onCancel={handleCancel}
      e
    >
      <Form onFinish={handleFinish} initialValues={jobLine} layout="vertical" autoComplete="off" form={form}>
        <LayoutFormRow grow>
          <Form.Item label={t("joblines.fields.line_no")} name="line_no">
            <InputNumber />
          </Form.Item>
          <Form.Item
            label={t("joblines.fields.line_desc")}
            rules={[
              {
                required: true
                //message: t("general.validation.required"),
              }
            ]}
            name="line_desc"
          >
            <Input.TextArea autoSize />
          </Form.Item>
          <JoblinesPreset form={form} />
        </LayoutFormRow>
        <LayoutFormRow grow>
          <Form.Item label={t("joblines.fields.mod_lbr_ty")} name="mod_lbr_ty">
            <Select allowClear options={[
              { value: "LAA", label: t("joblines.fields.lbr_types.LAA") },
              { value: "LAB", label: t("joblines.fields.lbr_types.LAB") },
              { value: "LAD", label: t("joblines.fields.lbr_types.LAD") },
              { value: "LAE", label: t("joblines.fields.lbr_types.LAE") },
              { value: "LAF", label: t("joblines.fields.lbr_types.LAF") },
              { value: "LAG", label: t("joblines.fields.lbr_types.LAG") },
              { value: "LAM", label: t("joblines.fields.lbr_types.LAM") },
              { value: "LAR", label: t("joblines.fields.lbr_types.LAR") },
              { value: "LAS", label: t("joblines.fields.lbr_types.LAS") },
              { value: "LAU", label: t("joblines.fields.lbr_types.LAU") },
              { value: "LA1", label: t("joblines.fields.lbr_types.LA1") },
              { value: "LA2", label: t("joblines.fields.lbr_types.LA2") },
              { value: "LA3", label: t("joblines.fields.lbr_types.LA3") },
              { value: "LA4", label: t("joblines.fields.lbr_types.LA4") }
            ]} />
          </Form.Item>
          <Form.Item label={t("joblines.fields.op_code_desc")} name="op_code_desc">
            <Input />
          </Form.Item>
          <Form.Item
            label={t("joblines.fields.mod_lb_hrs")}
            name="mod_lb_hrs"
            rules={[
              ({ getFieldValue }) => ({
                validator(rule, value) {
                  if (!!getFieldValue("mod_lbr_ty") === (!!value || value === 0)) {
                    return Promise.resolve();
                  }
                  return Promise.reject(t("joblines.validations.hrsrequirediflbrtyp"));
                }
              })
            ]}
          >
            <InputNumber precision={1} />
          </Form.Item>
          {Autohouse_Detail_line.treatment === "on" && (
            <Form.Item
              label={t("joblines.fields.ah_detail_line")}
              name="ah_detail_line"
              valuePropName="checked"
              dependencies={["mod_lbr_ty"]}
              initialValue={false}
              rules={[
                ({ getFieldValue }) => ({
                  validator(rule, value) {
                    if (value === false || value === undefined || value === null) return Promise.resolve();
                    if (value === true && ["LA1", "LA2", "LA3", "LA4", "LAU"].includes(getFieldValue("mod_lbr_ty"))) {
                      return Promise.resolve();
                    }
                    return Promise.reject(t("joblines.validations.ahdetailonlyonuserdefinedtypes"));
                  }
                })
              ]}
            >
              <Switch />
            </Form.Item>
          )}
        </LayoutFormRow>
        <LayoutFormRow>
          <Form.Item label={t("joblines.fields.part_type")} name="part_type">
            <Select allowClear options={[
              { value: "PAA", label: t("joblines.fields.part_types.PAA") },
              { value: "PAC", label: t("joblines.fields.part_types.PAC") },
              { value: "PAE", label: t("joblines.fields.part_types.PAE") },
              { value: "PAL", label: t("joblines.fields.part_types.PAL") },
              { value: "PAM", label: t("joblines.fields.part_types.PAM") },
              { value: "PAN", label: t("joblines.fields.part_types.PAN") },
              { value: "PAO", label: t("joblines.fields.part_types.PAO") },
              { value: "PAR", label: t("joblines.fields.part_types.PAR") },
              { value: "PAS", label: t("joblines.fields.part_types.PAS") }
            ]} />
          </Form.Item>
          <Form.Item label={t("joblines.fields.oem_partno")} name="oem_partno">
            <Input />
          </Form.Item>
          <Form.Item
            label={t("joblines.fields.part_qty")}
            name="part_qty"
            rules={[
              ({ getFieldValue }) => ({
                validator(rule, value) {
                  if (!!getFieldValue("part_type") === !!value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(t("joblines.validations.requiredifparttype"));
                }
              })
            ]}
          >
            <InputNumber precision={0} min={0} />
          </Form.Item>
          {/* <Form.Item label={t("joblines.fields.db_price")} name="db_price">
            <InputCurrency precision={2} min={0} />
          </Form.Item> */}
          <Form.Item
            label={t("joblines.fields.act_price")}
            name="act_price"
            rules={[
              ({ getFieldValue }) => ({
                validator(rule, value) {
                  if (!value || getFieldValue("part_type") !== "PAE") {
                    return Promise.resolve();
                  }
                  return Promise.reject(t("joblines.validations.zeropriceexistingpart"));
                }
              }),
              ({ getFieldValue }) => ({
                validator(rule, value) {
                  if (!!getFieldValue("part_type") === (!!value || value === 0)) {
                    return Promise.resolve();
                  }
                  return Promise.reject(t("joblines.validations.requiredifparttype"));
                }
              })
            ]}
          >
            <InputCurrency precision={2} min={Allow_Negative_Jobline_Price.treatment === "on" ? null : 0} />
          </Form.Item>
          <Form.Item label={t("joblines.fields.prt_dsmk_p")} name="prt_dsmk_p" initialValue={0}>
            <InputNumber precision={0} min={-100} max={100} />
          </Form.Item>
          <Form.Item label={t("joblines.fields.tax_part")} name="tax_part" valuePropName="checked" initialValue={true}>
            <Switch />
          </Form.Item>
          <Form.Item dependencies={[["act_price"]]} noStyle>
            {() => {
              if (form.getFieldValue("act_price") === 0) {
                return (
                  <Form.Item
                    label={t("joblines.fields.include_in_part_cnt")}
                    name="include_in_part_cnt"
                    valuePropName="checked"
                  >
                    <Switch />
                  </Form.Item>
                );
              } else {
                return null;
              }
            }}
          </Form.Item>
        </LayoutFormRow>
      </Form>
    </Modal>
  );
}
