import { useMutation } from "@apollo/client";
import { Dropdown, Menu, 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 { INSERT_APPOINTMENT_BLOCK } from "../../graphql/appointments.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { logImEXEvent } from "../../firebase/firebase.utils";

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();
    }
  };

  const menu = (
    <Menu onClick={handleMenu}>
      <Menu.Item key="block">{t("appointments.actions.block")}</Menu.Item>
    </Menu>
  );

  return (
    <Dropdown
      overlay={menu}
      disabled={alreadyBlocked}
      trigger={["contextMenu"]}
    >
      {children}
    </Dropdown>
  );
}
export default connect(mapStateToProps, mapDispatchToProps)(ScheduleBlockDay);
