import { DeleteFilled, DownOutlined, WarningFilled } from "@ant-design/icons";
import { useTreatmentsWithConfig } from "@splitsoftware/splitio-react";
import { Button, 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 CurrencyInput from "../form-items-formatted/currency-form-item.component";
import FormListMoveArrows from "../form-list-move-arrows/form-list-move-arrows.component";
import { getFormListItemTitle } from "../form-list-move-arrows/form-list-item-title.utils";
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";
import DateTimePicker from "../form-date-time-picker/form-date-time-picker.component.jsx";
import { selectIsPartsEntry } from "../../redux/application/application.selectors.js";

const PriceInputWrapper = ({ value, onChange, form, field }) => (
  <Space.Compact style={{ width: "100%" }}>
    <PartsOrderModalPriceChange form={form} field={field} />
    <CurrencyInput style={{ flex: 1 }} value={value} onChange={onChange} />
  </Space.Compact>
);

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

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

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

  const { t } = useTranslation();
  const partsOrderLines = Form.useWatch(["parts_order_lines", "data"], form) || [];
  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" hidden>
        <Input type="hidden" />
      </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?.special_coverage_policy && (
          <Tag color="tomato">
            <Space>
              <WarningFilled />
              <span>{t("jobs.labels.specialcoveragepolicy")}</span>
            </Space>
          </Tag>
        )}
        {!isReturn && !isPartsEntry && (
          <Form.Item
            name="removefrompartsqueue"
            label={t("parts_orders.labels.removefrompartsqueue")}
            valuePropName="checked"
          >
            <Checkbox />
          </Form.Item>
        )}
        {OEConnection.treatment === "on" && !isReturn && !isPartsEntry && (
          <Form.Item name="is_quote" label={t("parts_orders.labels.is_quote")} valuePropName="checked">
            <Checkbox />
          </Form.Item>
        )}

        <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 titlePlacement="left">{t("parts_orders.labels.inthisorder")}</Divider>
      <Form.List name={["parts_order_lines", "data"]}>
        {(fields, { remove, move }) => {
          return (
            <div>
              {fields.map((field, index) => {
                const partsOrderLine = partsOrderLines[field.name] || {};

                return (
                  <Form.Item required={false} key={field.key}>
                    <LayoutFormRow
                      grow
                      noDivider
                      title={getFormListItemTitle(
                        t("parts_orders.fields.line_desc"),
                        index,
                        partsOrderLine.line_desc,
                        partsOrderLine.oem_partno
                      )}
                      extra={
                        <Space align="center" size="small">
                          <Button
                            type="text"
                            icon={<DeleteFilled />}
                            onClick={() => {
                              remove(field.name);
                            }}
                          />
                          <FormListMoveArrows
                            move={move}
                            index={index}
                            total={fields.length}
                            orientation="horizontal"
                          />
                        </Space>
                      }
                    >
                      <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 key={`${index}job_line_id`} name={[field.name, "job_line_id"]} hidden>
                        <Input type="hidden" />
                      </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")}
                          options={[
                            { value: "PAA", label: t("joblines.fields.part_types.PAA") },
                            { value: "PAC", label: t("joblines.fields.part_types.PAC") },
                            { value: "PAL", label: t("joblines.fields.part_types.PAL") },
                            { value: "PAG", label: t("joblines.fields.part_types.PAG") },
                            { value: "PAM", label: t("joblines.fields.part_types.PAM") },
                            { value: "PAP", label: t("joblines.fields.part_types.PAP") },
                            { 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("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"]}
                      >
                        <PriceInputWrapper 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>
                  </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 && !isPartsEntry && (
                <Radio value={"oec"}>{t("parts_orders.labels.oec")}</Radio>
              )}
            </Radio.Group>
          );
        }}
      </Form.Item>
    </div>
  );
}
