import { useMutation } from "@apollo/client/react";
import { Button, Form, Popover, Spin } 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_UPDATE_BO_ETA } from "../../graphql/parts-orders.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { DateFormatter } from "../../utils/DateFormatter";
import { CalendarFilled } from "@ant-design/icons";
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 PartsOrderBackorderEta({ backordered_eta, partsOrderStatus, partsLineId, disabled, bodyshop }) {
  const [visibility, setVisibility] = useState(false);
  const [loading, setLoading] = useState(false);
  const [updateBoDate] = useMutation(MUTATION_UPDATE_BO_ETA);
  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_update_eta");

    const result = await updateBoDate({
      variables: {
        partsLineId,
        partsOrder: { backordered_eta: values.eta }
      }
    });

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

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

  const handlePopover = () => {
    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("general.actions.save")}
        </Button>
        <Button onClick={() => setVisibility(false)}>Close</Button>
      </Form>
    </div>
  );

  return (
    <Popover destroyOnHidden content={popContent} open={visibility} disabled={disabled}>
      <DateFormatter>{backordered_eta}</DateFormatter>
      {isAlreadyBackordered && <CalendarFilled style={{ cursor: "pointer" }} onClick={handlePopover} />}
      {loading && <Spin />}
    </Popover>
  );
}

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