import { DeleteFilled, DownOutlined, WarningFilled } from "@ant-design/icons";
import { useSplitTreatments } from "@splitsoftware/splitio-react";
import { Checkbox, Divider, Dropdown, Form, Input, InputNumber, Radio, Select, Space, Tag } from "antd";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import DateTimePicker from "../form-date-time-picker/form-date-time-picker.component.jsx";
import CurrencyInput from "../form-items-formatted/currency-form-item.component";
import FormListMoveArrows from "../form-list-move-arrows/form-list-move-arrows.component";
import LayoutFormRow from "../layout-form-row/layout-form-row.component";
import VendorSearchSelect from "../vendor-search-select/vendor-search-select.component";
import PartsOrderModalPriceChange from "./parts-order-modal-price-change.component";

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

export function PartsOrderModalComponent({ bodyshop, vendorList, sendTypeState, isReturn, preferredMake, job, form }) {
  const [sendType, setSendType] = sendTypeState;

  const {
    treatments: { OEConnection, OEConnection_PriceChange }
  } = useSplitTreatments({
    attributes: {},
    names: ["OEConnection", "OEConnection_PriceChange"],
    splitKey: bodyshop.imexshopid
  });

  const { t } = useTranslation();
  const handleClick = ({ item }) => {
    form.setFieldsValue({ comments: item.props.value });
  };

  const menu = {
    items: bodyshop.md_parts_order_comment.map((comment, idx) => ({
      key: idx,
      label: comment.label,
      value: comment.comment
    })),
    onClick: handleClick
  };

  return (
    <div>
      <Form.Item name="returnfrombill" style={{ display: "none" }}>
        <Input />
      </Form.Item>
      <LayoutFormRow grow noDivider>
        <Form.Item
          name="vendorid"
          label={t("vendors.fields.name")}
          rules={[
            {
              required: true
              //message: t("general.validation.required"),
            }
          ]}
        >
          <VendorSearchSelect options={vendorList} disabled={isReturn} preferredMake={preferredMake} showPhone />
        </Form.Item>
        <Form.Item
          name="deliver_by"
          rules={[
            {
              required: true
              //message: t("general.validation.required"),
            }
          ]}
          label={t("parts_orders.fields.deliver_by")}
        >
          <DateTimePicker isDateOnly onlyFuture />
        </Form.Item>
        {job && job.special_coverage_policy && (
          <Tag color="tomato">
            <Space>
              <WarningFilled />
              <span>{t("jobs.labels.specialcoveragepolicy")}</span>
            </Space>
          </Tag>
        )}
        {!isReturn && (
          <Form.Item
            name="removefrompartsqueue"
            label={t("parts_orders.labels.removefrompartsqueue")}
            valuePropName="checked"
          >
            <Checkbox />
          </Form.Item>
        )}
        {OEConnection.treatment === "on" && !isReturn && (
          <Form.Item name="is_quote" label={t("parts_orders.labels.is_quote")} valuePropName="checked">
            <Checkbox />
          </Form.Item>
        )}
        {!isReturn && (
          <Form.Item name="order_type" initialValue="parts_order" label={t("parts_orders.labels.order_type")}>
            <Radio.Group disabled={sendType === "oec"}>
              <Radio value={"parts_order"}>{t("parts_orders.labels.parts_order")}</Radio>
              <Radio value={"sublet"}>{t("parts_orders.labels.sublet_order")}</Radio>
            </Radio.Group>
          </Form.Item>
        )}
      </LayoutFormRow>
      <Divider orientation="left">{t("parts_orders.labels.inthisorder")}</Divider>
      <Form.List name={["parts_order_lines", "data"]}>
        {(fields, { remove, move }) => {
          return (
            <div>
              {fields.map((field, index) => (
                <Form.Item required={false} key={field.key}>
                  <div style={{ display: "flex" }}>
                    <LayoutFormRow grow noDivider style={{ flex: 1 }}>
                      <Form.Item
                        //span={8}
                        label={t("parts_orders.fields.line_desc")}
                        key={`${index}line_desc`}
                        name={[field.name, "line_desc"]}
                        rules={[
                          {
                            required: true
                            //message: t("general.validation.required"),
                          }
                        ]}
                      >
                        <Input />
                      </Form.Item>
                      <Form.Item
                        label={t("parts_orders.fields.line_remarks")}
                        key={`${index}line_remarks`}
                        name={[field.name, "line_remarks"]}
                      >
                        <Input />
                      </Form.Item>
                      <Form.Item
                        label={t("parts_orders.fields.part_type")}
                        key={`${index}part_type`}
                        name={[field.name, "part_type"]}
                      >
                        <Select disabled={!(sendType === "oec" && OEConnection_PriceChange.treatment === "on")}>
                          <Select.Option value="PAA">{t("joblines.fields.part_types.PAA")}</Select.Option>
                          <Select.Option value="PAC">{t("joblines.fields.part_types.PAC")}</Select.Option>

                          <Select.Option value="PAL">{t("joblines.fields.part_types.PAL")}</Select.Option>
                          <Select.Option value="PAG">{t("joblines.fields.part_types.PAG")}</Select.Option>
                          <Select.Option value="PAM">{t("joblines.fields.part_types.PAM")}</Select.Option>
                          <Select.Option value="PAP">{t("joblines.fields.part_types.PAP")}</Select.Option>
                          <Select.Option value="PAN">{t("joblines.fields.part_types.PAN")}</Select.Option>
                          <Select.Option value="PAO">{t("joblines.fields.part_types.PAO")}</Select.Option>
                          <Select.Option value="PAR">{t("joblines.fields.part_types.PAR")}</Select.Option>
                          <Select.Option value="PAS">{t("joblines.fields.part_types.PAS")}</Select.Option>
                        </Select>
                      </Form.Item>
                      <Form.Item
                        label={t("parts_orders.fields.oem_partno")}
                        key={`${index}oem_partno`}
                        name={[field.name, "oem_partno"]}
                      >
                        <Input />
                      </Form.Item>
                      {
                        // <Form.Item
                        //   label={t("parts_orders.fields.db_price")}
                        //   key={`${index}db_price`}
                        //   name={[field.name, "db_price"]}
                        // >
                        //   <CurrencyInput />
                        // </Form.Item>
                      }
                      <Form.Item
                        label={t("parts_orders.fields.quantity")}
                        key={`${index}quantity`}
                        name={[field.name, "quantity"]}
                        rules={[
                          {
                            required: true
                            //message: t("general.validation.required"),
                          }
                        ]}
                      >
                        <InputNumber min={1} />
                      </Form.Item>
                      <Form.Item
                        label={t("parts_orders.fields.act_price")}
                        key={`${index}act_price`}
                        name={[field.name, "act_price"]}
                      >
                        <CurrencyInput addonBefore={<PartsOrderModalPriceChange form={form} field={field} />} />
                      </Form.Item>
                      {isReturn && (
                        <Form.Item
                          label={t("parts_orders.fields.cost")}
                          key={`${index}cost`}
                          name={[field.name, "cost"]}
                        >
                          <CurrencyInput />
                        </Form.Item>
                      )}
                    </LayoutFormRow>
                    <Space wrap size="small" align="center">
                      <div>
                        <DeleteFilled
                          style={{ margin: "1rem" }}
                          onClick={() => {
                            remove(field.name);
                          }}
                        />
                      </div>
                      <FormListMoveArrows move={move} index={index} total={fields.length} />
                    </Space>
                  </div>
                </Form.Item>
              ))}
            </div>
          );
        }}
      </Form.List>
      <Form.Item
        name="comments"
        label={
          <Space>
            {t("parts_orders.fields.comments")}
            <Dropdown menu={menu}>
              <a className="ant-dropdown-link" href=" #" onClick={(e) => e.preventDefault()}>
                <DownOutlined />
              </a>
            </Dropdown>
          </Space>
        }
      >
        <Input.TextArea rows={3} />
      </Form.Item>

      <Form.Item noStyle shouldUpdate>
        {() => {
          const is_quote = form.getFieldValue("is_quote");
          if (is_quote) setSendType("oec");
          return (
            <Radio.Group defaultValue={sendType} value={sendType} onChange={(e) => setSendType(e.target.value)}>
              <Radio disabled={is_quote} value={"none"}>
                {t("general.labels.none")}
              </Radio>
              <Radio disabled={is_quote} value={"e"}>
                {t("parts_orders.labels.email")}
              </Radio>
              <Radio disabled={is_quote} value={"p"}>
                {t("parts_orders.labels.print")}
              </Radio>
              {OEConnection.treatment === "on" && !isReturn && (
                <Radio value={"oec"}>{t("parts_orders.labels.oec")}</Radio>
              )}
            </Radio.Group>
          );
        }}
      </Form.Item>
    </div>
  );
}
