import { useMutation } from "@apollo/client";
import { Button, Form, notification, Popover } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { MUTATION_BACKORDER_PART_LINE } from "../../graphql/parts-orders.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import FormDatePicker from "../form-date-picker/form-date-picker.component";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});

export function PartsOrderLineBackorderButton({ partsOrderStatus, partsLineId, jobLineId, disabled, bodyshop }) {
  const [visibility, setVisibility] = useState(false);
  const [loading, setLoading] = useState(false);
  const [backorderLine] = useMutation(MUTATION_BACKORDER_PART_LINE);
  const { t } = useTranslation();
  const [form] = Form.useForm();

  const isAlreadyBackordered = bodyshop.md_order_statuses.default_bo === partsOrderStatus;

  const handleFinish = async (values) => {
    setLoading(true);
    logImEXEvent("job_parts_backorder");

    const partsOrder = {
      status: isAlreadyBackordered
        ? bodyshop.md_order_statuses.default_received || "Received*"
        : bodyshop.md_order_statuses.default_bo || "Backordered*"
    };
    if (!isAlreadyBackordered) {
      partsOrder.backordered_on = new Date();
      partsOrder.backordered_eta = values.eta;
    }

    const result = await backorderLine({
      variables: {
        jobLineId,
        partsLineId,
        partsOrder: partsOrder,
        status: partsOrder.status
      }
    });

    if (!!result.errors) {
      notification["error"]({
        message: t("parts_orders.errors.backordering", {
          message: JSON.stringify(result.errors)
        })
      });
    }

    setVisibility(false);
    setLoading(false);
  };

  const handlePopover = (e) => {
    if (isAlreadyBackordered) {
      handleFinish();
      //Receive the part.
    } else {
      //Show the date selector to back order the part.
      setVisibility(true);
    }
  };

  const popContent = (
    <div>
      <Form form={form} onFinish={handleFinish}>
        <Form.Item name="eta">
          <FormDatePicker />
        </Form.Item>
        <Button type="primary" onClick={() => form.submit()}>
          {t("parts_orders.actions.backordered")}
        </Button>
        <Button onClick={() => setVisibility(false)}>Close</Button>
      </Form>
    </div>
  );

  return (
    <Popover destroyTooltipOnHide content={popContent} open={visibility} disabled={disabled}>
      <Button loading={loading} onClick={handlePopover}>
        {isAlreadyBackordered ? t("parts_orders.actions.receive") : t("parts_orders.actions.backordered")}
      </Button>
    </Popover>
  );
}

export default connect(mapStateToProps, null)(PartsOrderLineBackorderButton);
