import { FileAddFilled } from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import { Button, notification, Tooltip } from "antd";
import { t } from "i18next";
import moment from "moment";
import React, { useState } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { INSERT_INVENTORY_AND_CREDIT } from "../../graphql/inventory.queries";
import {
  selectBodyshop,
  selectCurrentUser,
} from "../../redux/user/user.selectors";
import { CalculateBillTotal } from "../bill-form/bill-form.totals.utility";
import queryString from "query-string";
import { useLocation } from "react-router-dom";

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

export function BilllineAddInventory({
  currentUser,
  bodyshop,
  billline,
  disabled,
  jobid,
}) {
  const [loading, setLoading] = useState(false);
  const { billid } = queryString.parse(useLocation().search);

  const [insertInventoryLine] = useMutation(INSERT_INVENTORY_AND_CREDIT);

  const addToInventory = async () => {
    setLoading(true);

    //Check to  make sure there are no existing items already in the inventory.

    const cm = {
      vendorid: bodyshop.inhousevendorid,
      invoice_number: "ih",
      jobid: jobid,
      isinhouse: true,
      is_credit_memo: true,
      date: moment().format("YYYY-MM-DD"),
      federal_tax_rate: bodyshop.bill_tax_rates.federal_tax_rate,
      state_tax_rate: bodyshop.bill_tax_rates.state_tax_rate,
      local_tax_rate: bodyshop.bill_tax_rates.local_tax_rate,
      total: 0,
      billlines: [
        {
          actual_price: billline.actual_price,
          actual_cost: billline.actual_cost,
          quantity: billline.quantity,
          line_desc: billline.line_desc,
          cost_center: billline.cost_center,
          deductedfromlbr: billline.deductedfromlbr,
          applicable_taxes: {
            local: billline.applicable_taxes.local,
            state: billline.applicable_taxes.state,
            federal: billline.applicable_taxes.federal,
          },
        },
      ],
    };

    cm.total = CalculateBillTotal(cm).enteredTotal.getAmount() / 100;

    const insertResult = await insertInventoryLine({
      variables: {
        joblineId:
          billline.joblineid === "noline" ? billline.id : billline.joblineid, //This will return null as there will be no jobline that has the id of the bill line.
        //Unfortunately, we can't send null as the GQL syntax validation fails.
        joblineStatus: bodyshop.md_order_statuses.default_returned,
        inv: {
          shopid: bodyshop.id,
          billlineid: billline.id,
          actual_price: billline.actual_price,
          actual_cost: billline.actual_cost,
          quantity: billline.quantity,
          line_desc: billline.line_desc,
        },
        cm: { ...cm, billlines: { data: cm.billlines } }, //Fix structure for apollo insert.
        pol: {
          returnfrombill: billid,
          vendorid: bodyshop.inhousevendorid,
          deliver_by: moment().format("YYYY-MM-DD"),
          parts_order_lines: {
            data: [
              {
                line_desc: billline.line_desc,

                act_price: billline.actual_price,
                cost: billline.actual_cost,
                quantity: billline.quantity,
                job_line_id:
                  billline.joblineid === "noline" ? null : billline.joblineid,
                part_type: billline.jobline && billline.jobline.part_type,
                cm_received: true,
              },
            ],
          },
          order_date: "2022-06-01",
          orderedby: currentUser.email,
          jobid: jobid,
          user_email: currentUser.email,
          return: true,
          status: "Ordered",
        },
      },
      refetchQueries: ["QUERY_BILL_BY_PK"],
    });

    if (!insertResult.errors) {
      notification.open({
        type: "success",
        message: t("inventory.successes.inserted"),
      });
    } else {
      notification.open({
        type: "error",
        message: t("inventory.errors.inserting", {
          error: JSON.stringify(insertResult.errors),
        }),
      });
    }

    setLoading(false);
  };

  return (
    <Tooltip title={t("inventory.actions.addtoinventory")}>
      <Button
        loading={loading}
        disabled={
          disabled || billline?.inventories?.length >= billline.quantity
        }
        onClick={addToInventory}
      >
        <FileAddFilled />
        {billline?.inventories?.length > 0 && (
          <div>({billline?.inventories?.length} in inv)</div>
        )}
      </Button>
    </Tooltip>
  );
}
