import { Button, Checkbox, Form, Modal } from "antd";
import queryString from "query-string";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { setModalContext } from "../../redux/modals/modals.actions";
import ReadOnlyFormItemComponent from "../form-items-formatted/read-only-form-item.component";

const mapStateToProps = createStructuredSelector({});

const mapDispatchToProps = (dispatch) => ({
  setPartsOrderContext: (context) =>
    dispatch(
      setModalContext({
        context: context,
        modal: "partsOrder"
      })
    )
});

export default connect(mapStateToProps, mapDispatchToProps)(BillDetailEditReturn);

export function BillDetailEditReturn({ setPartsOrderContext, data, disabled }) {
  const search = queryString.parse(useLocation().search);
  const history = useNavigate();
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const [open, setOpen] = useState(false);
  const initialValues =
    data && data.bills_by_pk
      ? {
          ...data.bills_by_pk,
          billlines: (data.bills_by_pk.billlines || []).map((bl) => {
            const oem = bl.oem_partno || (bl.jobline && bl.jobline.oem_partno) || "";
            const alt = bl.alt_partno || (bl.jobline && bl.jobline.alt_partno) || "";
            return {
              ...bl,
              oem_partno: `${oem || ""} ${alt ? `(${alt})` : ""}`.trim()
            };
          })
        }
      : undefined;

  const handleFinish = ({ billlines }) => {
    const selectedLines = billlines.filter((l) => l.selected).map((l) => l.id);

    setPartsOrderContext({
      actions: {},
      context: {
        jobId: data.bills_by_pk.jobid,
        job: data.bills_by_pk.job,
        vendorId: data.bills_by_pk.vendorid,
        returnFromBill: data.bills_by_pk.id,
        invoiceNumber: data.bills_by_pk.invoice_number,
        linesToOrder: data.bills_by_pk.billlines
          .filter((l) => selectedLines.includes(l.id))
          .map((i) => {
            return {
              line_desc: i.line_desc,
              //  db_price: i.actual_price,
              act_price: i.actual_price,
              cost: i.actual_cost,
              part_qty: i.quantity,
              joblineid: i.joblineid,
              oem_partno: i.jobline && i.jobline.oem_partno,
              part_type: i.jobline && i.jobline.part_type
            };
          }),
        isReturn: true
      }
    });
    delete search.billid;

    history({ search: queryString.stringify(search) });
    setOpen(false);
  };
  useEffect(() => {
    if (open === false) form.resetFields();
  }, [open, form]);

  return (
    <>
      <Modal
        open={open}
        onCancel={() => setOpen(false)}
        destroyOnHidden
        title={t("bills.actions.return")}
        onOk={() => form.submit()}
        width={700}
      >
        <Form initialValues={initialValues} onFinish={handleFinish} form={form}>
          <Form.List name={["billlines"]}>
            {(fields) => {
              return (
                <table style={{ tableLayout: "auto", width: "100%" }}>
                  <thead>
                    <tr>
                      <td>
                        <Checkbox
                          onChange={(e) => {
                            form.setFieldsValue({
                              billlines: form.getFieldsValue().billlines.map((b) => ({
                                ...b,
                                selected: e.target.checked
                              }))
                            });
                          }}
                        />
                      </td>
                      <td>{t("billlines.fields.line_desc")}</td>
                      <td>{t("billlines.fields.oem_partno")}</td>
                      <td style={{ textAlign: "right" }}>{t("billlines.fields.quantity")}</td>
                      <td style={{ textAlign: "right" }}>{t("billlines.fields.actual_price")}</td>
                      <td style={{ textAlign: "right" }}>{t("billlines.fields.actual_cost")}</td>
                    </tr>
                  </thead>
                  <tbody>
                    {fields.map((field, index) => (
                      <tr key={field.key}>
                        <td>
                          {/* Hidden field to preserve the id */}
                          <Form.Item name={[field.name, "id"]} hidden>
                            <input type="hidden" />
                          </Form.Item>
                          <Form.Item
                            //   label={t("joblines.fields.selected")}
                            key={`${index}selected`}
                            name={[field.name, "selected"]}
                            valuePropName="checked"
                          >
                            <Checkbox />
                          </Form.Item>
                        </td>
                        <td>
                          <Form.Item
                            //   label={t("joblines.fields.line_desc")}
                            key={`${index}line_desc`}
                            name={[field.name, "line_desc"]}
                          >
                            <ReadOnlyFormItemComponent />
                          </Form.Item>
                        </td>
                        <td>
                          <Form.Item
                            //   label={t("joblines.fields.oem_partno")}
                            key={`${index}jobline.oem_partno`}
                            name={[field.name, "oem_partno"]}
                          >
                            <ReadOnlyFormItemComponent />
                          </Form.Item>
                        </td>
                        <td style={{ textAlign: "right" }}>
                          <Form.Item
                            //   label={t("joblines.fields.quantity")}
                            key={`${index}quantity`}
                            name={[field.name, "quantity"]}
                          >
                            <ReadOnlyFormItemComponent />
                          </Form.Item>
                        </td>
                        <td style={{ textAlign: "right" }}>
                          <Form.Item
                            //   label={t("joblines.fields.actual_price")}
                            key={`${index}actual_price`}
                            name={[field.name, "actual_price"]}
                          >
                            <ReadOnlyFormItemComponent type="currency" />
                          </Form.Item>
                        </td>
                        <td style={{ textAlign: "right" }}>
                          <Form.Item
                            //   label={t("joblines.fields.actual_cost")}
                            key={`${index}actual_cost`}
                            name={[field.name, "actual_cost"]}
                          >
                            <ReadOnlyFormItemComponent type="currency" />
                          </Form.Item>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              );
            }}
          </Form.List>
        </Form>
      </Modal>
      <Button
        disabled={data.bills_by_pk.is_credit_memo || data.bills_by_pk.isinhouse || disabled}
        onClick={() => {
          setOpen(true);
        }}
      >
        {t("bills.actions.return")}
      </Button>
    </>
  );
}
