import { useMutation } from "@apollo/client/react";
import { Button, Popconfirm } from "antd";
import queryString from "query-string";
import { useTranslation } from "react-i18next";
import { useLocation, useNavigate } from "react-router-dom";
import { DELETE_TEMPLATE } from "../../graphql/templates.queries";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

export default function ShopTemplateDeleteComponent({ templateId, refetch }) {
  const { t } = useTranslation();
  const search = queryString.parse(useLocation().search);
  const history = useNavigate();
  const [deleteTemplate] = useMutation(DELETE_TEMPLATE);
  const notification = useNotification();

  const handleDelete = async () => {
    logImEXEvent("shop_template_delete");

    const result = await deleteTemplate({
      variables: {
        templateId: templateId
      }
    });

    if (result.errors) {
      notification.error({
        title: t("bodyshop.errors.deletingtemplate", {
          message: JSON.stringify(result.errors)
        })
      });
    } else {
      delete search.customTemplateId;
      history({ search: queryString.stringify(search) });
      if (refetch) refetch();
    }
  };

  return (
    <Popconfirm
      title={t("general.labels.areyousure")}
      okText={t("general.labels.yes")}
      cancelText={t("general.labels.no")}
      onConfirm={handleDelete}
    >
      <Button>{t("general.actions.delete")}</Button>
    </Popconfirm>
  );
}
