import { useMutation } from "@apollo/client/react";
import { Dropdown } from "antd";
import dayjs from "../../utils/day";
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";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

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

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

  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: dayjs(date).startOf("day"),
        end: dayjs(date).endOf("day")
      };
      logImEXEvent("dashboard_change_layout");

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

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

      if (refetch) refetch();
    }
  };

  const menu = {
    items: [
      {
        key: "block",
        label: t("appointments.actions.block")
      }
    ],
    onClick: handleMenu
  };

  return (
    <Dropdown menu={menu} disabled={alreadyBlocked} trigger={["contextMenu"]}>
      {children}
    </Dropdown>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(ScheduleBlockDay);
