import React, { useState } from "react";
import { notification } from "antd";
import { useLazyQuery, useQuery, useMutation } from "react-apollo";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { GET_JOB_LINES_TO_ENTER_INVOICE } from "../../graphql/jobs-lines.queries";
import { ACTIVE_JOBS_FOR_AUTOCOMPLETE } from "../../graphql/jobs.queries";
import { SEARCH_VENDOR_AUTOCOMPLETE } from "../../graphql/vendors.queries";
import { toggleModalVisible } from "../../redux/modals/modals.actions";
import { selectInvoiceEnterModal } from "../../redux/modals/modals.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import InvoiceEnterModalComponent from "./invoice-enter-modal.component";
import { INSERT_NEW_INVOICE } from "../../graphql/invoices.queries";
import { useTranslation } from "react-i18next";

const mapStateToProps = createStructuredSelector({
  invoiceEnterModal: selectInvoiceEnterModal,
  bodyshop: selectBodyshop
});
const mapDispatchToProps = dispatch => ({
  toggleModalVisible: () => dispatch(toggleModalVisible("invoiceEnter"))
});

function InvoiceEnterModalContainer({
  invoiceEnterModal,
  toggleModalVisible,
  bodyshop
}) {
  const { t } = useTranslation();
  const linesState = useState([]);
  const roSearchState = useState({ text: "", selectedId: null });
  const [roSearch, setRoSearch] = roSearchState;

  const [insertInvoice] = useMutation(INSERT_NEW_INVOICE);

  const { data: RoAutoCompleteData } = useQuery(ACTIVE_JOBS_FOR_AUTOCOMPLETE, {
    fetchPolicy: "network-only",
    variables: { statuses: bodyshop.md_ro_statuses.open_statuses || ["Open"] },
    skip: !invoiceEnterModal.visible
  });

  const vendorSearchState = useState({
    text: "",
    selectedId: null
  });
  const [vendorSearch, setVendorSearch] = vendorSearchState;
  const { data: VendorAutoCompleteData } = useQuery(
    SEARCH_VENDOR_AUTOCOMPLETE,
    {
      fetchPolicy: "network-only",
      skip: !invoiceEnterModal.visible
    }
  );

  const [loadLines, { called, data: lineData }] = useLazyQuery(
    GET_JOB_LINES_TO_ENTER_INVOICE,
    {
      fetchPolicy: "network-only",
      variables: { id: roSearch.selectedId }
    }
  );

  if (roSearch.selectedId) {
    if (!called) loadLines();
  }
  const handleRoSelect = (value, obj) => {
    setRoSearch({ ...roSearch, selectedId: obj.key });
  };

  const handleVendorSelect = (value, obj) => {
    setVendorSearch({ ...vendorSearch, selectedId: obj.key });
  };

  const handleFinish = values => {
    console.log("values", values);
    console.log(
      "Assigned",
      Object.assign(
        {},
        values,
        { jobid: roSearch.selectedId },
        { vendorid: vendorSearch.selectedId },
        {
          invoicelines: {
            data: values.invoicelines.map(item => delete item.joblinename)
          }
        }
      )
    );

    insertInvoice({
      variables: {
        invoice: [
          Object.assign(
            {},
            values,
            { jobid: roSearch.selectedId },
            { vendorid: vendorSearch.selectedId },
            { invoicelines: { data: values.invoicelines } }
          )
        ]
      }
    })
      .then(r => {
        // if (jobLineEditModal.actions.refetch)
        //   jobLineEditModal.actions.refetch();
        // toggleModalVisible();
        notification["success"]({
          message: t("invoices.successes.created")
        });
      })
      .catch(error => {
        console.log("error", error);

        notification["error"]({
          message: t("invoices.errors.creating", {
            message: error.message
          })
        });
      });
  };

  const handleCancel = () => {
    toggleModalVisible();
  };

  return (
    <InvoiceEnterModalComponent
      visible={invoiceEnterModal.visible}
      invoice={invoiceEnterModal.context}
      handleFinish={handleFinish}
      handleCancel={handleCancel}
      handleRoSelect={handleRoSelect}
      roAutoCompleteOptions={RoAutoCompleteData && RoAutoCompleteData.jobs}
      handleVendorSelect={handleVendorSelect}
      vendorAutoCompleteOptions={
        VendorAutoCompleteData && VendorAutoCompleteData.vendors
      }
      linesState={linesState}
      lineData={lineData ? lineData.joblines : null}
      vendor={
        vendorSearch.selectedId
          ? VendorAutoCompleteData &&
            VendorAutoCompleteData.vendors.filter(
              v => v.id === vendorSearch.selectedId
            )[0]
          : null
      }
      job={invoiceEnterModal.context.job || null}
      responsibilityCenters={bodyshop.md_responsibility_centers || null}
    />
  );
}

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