import { useMutation } from "@apollo/client/react";
import { Button, Form, Popover } from "antd";
import { 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 DateTimePicker from "../form-date-time-picker/form-date-time-picker.component.jsx";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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 notification = useNotification();

  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({
        title: t("parts_orders.errors.backordering", {
          message: JSON.stringify(result.errors)
        })
      });
    }

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

  const handlePopover = () => {
    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">
          <DateTimePicker isDateOnly />
        </Form.Item>
        <Button type="primary" onClick={() => form.submit()}>
          {t("parts_orders.actions.backordered")}
        </Button>
        <Button onClick={() => setVisibility(false)}>Close</Button>
      </Form>
    </div>
  );

  return (
    <Popover destroyOnHidden 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);
