import { useMutation } from "@apollo/client/react";
import { Button, Popconfirm } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { INSERT_EXPORT_LOG } from "../../graphql/accounting.queries";
import { UPDATE_JOBS } from "../../graphql/jobs.queries";
import { insertAuditTrail } from "../../redux/application/application.actions";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";
import AuditTrailMapping from "../../utils/AuditTrailMappings";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

const mapDispatchToProps = (dispatch) => ({
  insertAuditTrail: ({ jobid, operation, type }) => dispatch(insertAuditTrail({ jobid, operation, type }))
});

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

export function JobMarkSelectedExported({
  bodyshop,
  currentUser,
  jobIds,
  disabled,
  loadingCallback,
  completedCallback,
  refetch,
  insertAuditTrail
}) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [insertExportLog] = useMutation(INSERT_EXPORT_LOG);
  const notification = useNotification();

  const [updateJob] = useMutation(UPDATE_JOBS);
  const handleUpdate = async () => {
    setLoading(true);
    loadingCallback(true);
    const result = await updateJob({
      variables: {
        jobIds: jobIds,
        fields: {
          status: bodyshop.md_ro_statuses.default_exported || "Exported*",
          date_exported: new Date()
        }
      },
      update() {
        // NO OP
      }
    });

    await insertExportLog({
      variables: {
        logs: jobIds.map((id) => {
          return {
            bodyshopid: bodyshop.id,
            jobid: id,
            successful: true,
            message: JSON.stringify([t("general.labels.markedexported")]),
            useremail: currentUser.email
          };
        })
      }
    });

    if (!result.errors) {
      notification.success({ title: t("jobs.successes.save") });
      result.data.update_jobs.returning.forEach((job) => {
        console.log("results job", job.id, "audit: ", AuditTrailMapping.admin_jobmarkexported());
        insertAuditTrail({
          jobid: job.id,
          operation: AuditTrailMapping.admin_jobmarkexported(),
          type: "admin_jobmarkexported"
        });
      });
    } else {
      notification.error({
        title: t("jobs.errors.saving", {
          error: JSON.stringify(result.errors)
        })
      });
    }
    loadingCallback(false);
    completedCallback && completedCallback([]);
    setLoading(false);
    refetch && refetch();
    setOpen(false);
  };

  return (
    <Popconfirm
      open={open}
      title={t("general.labels.areyousure")}
      onCancel={() => setOpen(false)}
      onConfirm={handleUpdate}
      disabled={disabled}
    >
      <Button loading={loading} disabled={disabled} onClick={() => setOpen(true)} type="primary" danger>
        {t("jobs.actions.markasexported")}
      </Button>
    </Popconfirm>
  );
}
