import { QuestionCircleOutlined } from "@ant-design/icons";
import { Button, Popconfirm } from "antd";
import axios from "axios";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { logImEXEvent } from "../../firebase/firebase.utils.js";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";
import { isFunction } from "lodash";

/*
################################################################################################
 Developer Note:
 Known Technical Debt Item
         Modifications to this code requires complementary changes to the Cloudinary code. Cloudinary code will be removed upon completed migration.
################################################################################################
*/

export default function JobsDocumentsImgproxyDeleteButton({ galleryImages, deletionCallback }) {
  const { t } = useTranslation();
  const notification = useNotification();

  const imagesToDelete = [
    ...galleryImages.images.filter((image) => image.isSelected),
    ...galleryImages.other.filter((image) => image.isSelected)
  ];
  const [loading, setLoading] = useState(false);

  const handleDelete = async () => {
    logImEXEvent("job_documents_delete", { count: imagesToDelete.length });
    try {
      setLoading(true);
      const res = await axios.post("/media/imgproxy/delete", {
        ids: imagesToDelete.map((d) => d.id)
      });

      if (res.data.error) {
        notification.error({
          message: t("documents.errors.deleting", {
            error: JSON.stringify(res.data.error.response.errors)
          })
        });
      } else {
        notification.success({
          key: "docdeletedsuccesfully",
          message: t("documents.successes.delete")
        });

        if (isFunction(deletionCallback)) deletionCallback();
      }
    } catch (error) {
      notification.error({
        message: t("documents.errors.deleting", {
          error: error.message
        })
      });
    }
    setLoading(false);
  };

  return (
    <Popconfirm
      disabled={imagesToDelete.length < 1}
      icon={<QuestionCircleOutlined style={{ color: "red" }} />}
      onConfirm={handleDelete}
      title={t("documents.labels.confirmdelete")}
      okText={t("general.actions.delete")}
      okButtonProps={{ danger: true }}
      cancelText={t("general.actions.cancel")}
    >
      <Button disabled={imagesToDelete.length < 1} loading={loading}>
        {t("documents.actions.delete")}
      </Button>
    </Popconfirm>
  );
}
