import { QuestionCircleOutlined } from "@ant-design/icons";
import { Button, Popconfirm } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { logImEXEvent } from "../../firebase/firebase.utils";
import cleanAxios from "../../utils/CleanAxios";
//Context: currentUserEmail, bodyshop, jobid, invoiceid
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { getJobMedia } from "../../redux/media/media.actions";
import { selectAllMedia } from "../../redux/media/media.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

const mapStateToProps = createStructuredSelector({
  allMedia: selectAllMedia,

  bodyshop: selectBodyshop
});
const mapDispatchToProps = (dispatch) => ({
  getJobMedia: (id) => dispatch(getJobMedia(id))
});
export default connect(mapStateToProps, mapDispatchToProps)(JobsDocumentsLocalDeleteButton);

export function JobsDocumentsLocalDeleteButton({ bodyshop, getJobMedia, allMedia, jobid }) {
  const { t } = useTranslation();
  const notification = useNotification();

  const [loading, setLoading] = useState(false);

  const imagesToDelete = (allMedia?.[jobid] || []).filter((i) => i.isSelected);

  const handleDelete = async () => {
    logImEXEvent("job_documents_delete");
    setLoading(true);

    const delres = await cleanAxios.post(
      `${bodyshop.localmediaserverhttp}/jobs/delete`,
      {
        jobid: jobid,
        files: imagesToDelete.map((i) => i.filename)
      },
      { headers: { ims_token: bodyshop.localmediatoken } }
    );

    if (delres.errors) {
      notification.error({
        title: t("documents.errors.deleting", {
          message: JSON.stringify(delres.errors)
        })
      });
    } else {
      notification.success({
        key: "docdeletedsuccesfully",
        title: t("documents.successes.delete")
      });
    }
    getJobMedia(jobid);
    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 danger disabled={imagesToDelete.length < 1} loading={loading}>
        {t("documents.actions.delete")}
      </Button>
    </Popconfirm>
  );
}
