import { Modal, notification } from "antd";
import React, { useState, useEffect } from "react";
import { useMutation, useQuery } from "react-apollo";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { INSERT_NEW_PARTS_ORDERS } from "../../graphql/parts-orders.queries";
import { UPDATE_JOB_LINE_STATUS } from "../../graphql/jobs-lines.queries";
import { QUERY_ALL_VENDORS_FOR_ORDER } from "../../graphql/vendors.queries";
import {
  selectBodyshop,
  selectCurrentUser
} from "../../redux/user/user.selectors";
import AlertComponent from "../alert/alert.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import PartsOrderModalComponent from "./parts-order-modal.component";
import {
  setEmailOptions,
  toggleEmailOverlayVisible
} from "../../redux/email/email.actions";
import PartsOrderEmailTemplate from "../../emails/templates/parts-order/parts-order.email";
import { REPORT_QUERY_PARTS_ORDER_BY_PK } from "../../emails/templates/parts-order/parts-order.query";

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser,
  bodyshop: selectBodyshop
});
const mapDispatchToProps = dispatch => ({
  setEmailOptions: e => dispatch(setEmailOptions(e)),
  toggleEmailOverlayVisible: () => dispatch(toggleEmailOverlayVisible())
});
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(function PartsOrderModalContainer({
  partsOrderModalVisible,
  linesToOrder,
  jobId,
  currentUser,
  bodyshop,
  refetch,
  setEmailOptions,
  toggleEmailOverlayVisible
}) {
  const { t } = useTranslation();
  const [modalVisible, setModalVisible] = partsOrderModalVisible;

  //set order lines to be a version of the incoming lines.
  const orderLinesState = useState(
    linesToOrder.reduce((acc, value) => {
      acc.push({
        line_desc: value.line_desc,
        oem_partno: value.oem_partno,
        db_price: value.db_price,
        act_price: value.act_price,
        line_remarks: "Alalala",
        job_line_id: value.id,
        status: bodyshop.md_order_statuses.default_ordered || "Ordered*"
      });
      return acc;
    }, [])
  );
  const [orderLines, setOrderLinesState] = orderLinesState;
  useEffect(() => {
    if (modalVisible)
      setOrderLinesState(
        linesToOrder.reduce((acc, value) => {
          acc.push({
            line_desc: value.line_desc,
            oem_partno: value.oem_partno,
            db_price: value.db_price,
            act_price: value.act_price,
            line_remarks: "Alalala",
            job_line_id: value.id,
            status: bodyshop.md_order_statuses.default_ordered || "Ordered*"
          });
          return acc;
        }, [])
      );
  }, [
    modalVisible,
    setOrderLinesState,
    linesToOrder,
    bodyshop.md_order_statuses.default_ordered
  ]);

  const sendTypeState = useState("e");
  const sendType = sendTypeState[0];
  const partsOrderState = useState({
    vendorid: null,
    jobid: jobId,
    user_email: currentUser.email
  });
  const partsOrder = partsOrderState[0];

  const { loading, error, data } = useQuery(QUERY_ALL_VENDORS_FOR_ORDER, {
    fetchPolicy: "network-only",
    skip: !modalVisible
  });
  const [insertPartOrder] = useMutation(INSERT_NEW_PARTS_ORDERS);
  const [updateJobLines] = useMutation(UPDATE_JOB_LINE_STATUS);

  const handleOk = () => {
    insertPartOrder({
      variables: {
        po: [
          {
            ...partsOrder,
            status: bodyshop.md_order_statuses.default_ordered || "Ordered*",
            parts_order_lines: {
              data: orderLines
            }
          }
        ]
      }
    })
      .then(r => {
        updateJobLines({
          variables: {
            ids: linesToOrder.map(item => item.id),
            status: bodyshop.md_order_statuses.default_ordered || "Ordered*"
          }
        })
          .then(response => {
            notification["success"]({
              message: t("parts_orders.successes.created")
            });
            if (refetch) refetch();
            setModalVisible(false);

            if (sendType === "e") {
              //Show the email modal and set the data.

              //TODO Remove hardcoding
              setEmailOptions({
                messageOptions: {
                  from: {
                    name: "Kavia Autobdoy",
                    address: "noreply@bodyshop.app"
                  },
                  to: "patrickwf@gmail.com",
                  replyTo: "snaptsoft@gmail.com"
                },
                template: PartsOrderEmailTemplate,
                queryConfig: [
                  REPORT_QUERY_PARTS_ORDER_BY_PK,
                  {
                    variables: {
                      id: r.data.insert_parts_orders.returning[0].id
                    }
                  }
                ]
              });
              //toggleEmailOverlayVisible();
            }
          })
          .catch(error => {
            notification["error"]({
              message: t("parts_orders.errors.creating"),
              description: error.message
            });
          });
      })
      .catch(error => {
        notification["error"]({
          message: t("parts_orders.errors.creating"),
          description: error.message
        });
      });
  };

  return (
    <Modal
      visible={modalVisible}
      onCancel={() => setModalVisible(false)}
      onOk={handleOk}
    >
      {error ? <AlertComponent message={error.message} type="error" /> : null}
      <LoadingSpinner loading={loading}>
        <PartsOrderModalComponent
          vendorList={(data && data.vendors) || []}
          state={partsOrderState}
          sendTypeState={sendTypeState}
          orderLinesState={orderLinesState}
        />
      </LoadingSpinner>
    </Modal>
  );
});
