import { useMutation } from "@apollo/client";
import { Dropdown, notification } from "antd";
import moment from "moment";
import React from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { INSERT_APPOINTMENT_BLOCK } from "../../graphql/appointments.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";

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

const mapDispatchToProps = (dispatch) => ({});

export function ScheduleBlockDay({
  date,
  children,
  refetch,
  bodyshop,
  alreadyBlocked,
}) {
  const { t } = useTranslation();
  const [insertBlock] = useMutation(INSERT_APPOINTMENT_BLOCK);

  const handleMenu = async (e) => {
    e.domEvent.stopPropagation();

    if (e.key === "block") {
      const blockAppt = {
        title: t("appointments.labels.blocked"),
        block: true,
        isintake: false,
        bodyshopid: bodyshop.id,
        start: moment(date).startOf("day"),
        end: moment(date).endOf("day"),
      };
      logImEXEvent("dashboard_change_layout");

      const result = await insertBlock({
        variables: { app: [blockAppt] },
      });

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

      if (!!refetch) refetch();
    }
  };

  return (
    <Dropdown
      menu={{
        onClick: handleMenu,
        items: [{ key: 'block', label: t("appointments.actions.block") }],
      }}
      disabled={alreadyBlocked}
      trigger={["contextMenu"]}
    >
      {children}
    </Dropdown>
  );
}
export default connect(mapStateToProps, mapDispatchToProps)(ScheduleBlockDay);
