import { useMutation } from "@apollo/client";
import { Button, notification } from "antd";
import { gql } from "@apollo/client";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import {
  selectBodyshop,
  selectCurrentUser,
} from "../../redux/user/user.selectors";
import moment from "moment";
import AuditTrailMapping from "../../utils/AuditTrailMappings";
import { insertAuditTrail } from "../../redux/application/application.actions";
import { INSERT_EXPORT_LOG } from "../../graphql/accounting.queries";
const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  currentUser: selectCurrentUser,
});
const mapDispatchToProps = (dispatch) => ({
  insertAuditTrail: ({ jobid, operation }) =>
    dispatch(insertAuditTrail({ jobid, operation })),
});
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(JobAdminMarkReexport);

export function JobAdminMarkReexport({
  insertAuditTrail,
  bodyshop,
  currentUser,
  job,
}) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [insertExportLog] = useMutation(INSERT_EXPORT_LOG);
  const [markJobForReexport] = useMutation(gql`
    mutation MARK_JOB_FOR_REEXPORT($jobId: uuid!) {
      update_jobs_by_pk(
        pk_columns: { id: $jobId }
        _set: { date_exported: null
        status: "${bodyshop.md_ro_statuses.default_invoiced}"
        }
      ) {
        id
        date_exported
        status
        date_invoiced
      }
    }
  `);

  const [markJobExported] = useMutation(gql`
    mutation MARK_JOB_AS_EXPORTED($jobId: uuid!, $date_exported: timestamptz!) {
      update_jobs_by_pk(
        pk_columns: { id: $jobId }
        _set: { date_exported: $date_exported
        status: "${bodyshop.md_ro_statuses.default_exported}"
        }
      ) {
        id
        date_exported
        date_invoiced
        status
      }
    }
  `);
  const [markJobUninvoiced] = useMutation(gql`
    mutation MARK_JOB_AS_UNINVOICED($jobId: uuid!, ) {
      update_jobs_by_pk(
        pk_columns: { id: $jobId }
        _set: { date_exported: null
          date_invoiced: null
        status: "${bodyshop.md_ro_statuses.default_delivered}"
        }
      ) {
        id
        date_exported
        date_invoiced
        status
      }
    }
  `);

  const handleMarkForExport = async () => {
    setLoading(true);
    const result = await markJobForReexport({
      variables: { jobId: job.id },
    });

    if (!result.errors) {
      notification["success"]({ message: t("jobs.successes.save") });
      insertAuditTrail({
        jobid: job.id,
        operation: AuditTrailMapping.admin_jobmarkforreexport(),
      });
    } else {
      notification["error"]({
        message: t("jobs.errors.saving", {
          error: JSON.stringify(result.errors),
        }),
      });
    }
    setLoading(false);
  };

  const handleMarkExported = async () => {
    setLoading(true);
    const result = await markJobExported({
      variables: { jobId: job.id, date_exported: moment() },
    });

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

    if (!result.errors) {
      notification["success"]({ message: t("jobs.successes.save") });
      insertAuditTrail({
        jobid: job.id,
        operation: AuditTrailMapping.admin_jobmarkexported(),
      });
    } else {
      notification["error"]({
        message: t("jobs.errors.saving", {
          error: JSON.stringify(result.errors),
        }),
      });
    }
    setLoading(false);
  };

  const handleUninvoice = async () => {
    setLoading(true);
    const result = await markJobUninvoiced({
      variables: { jobId: job.id },
    });

    if (!result.errors) {
      notification["success"]({ message: t("jobs.successes.save") });
    } else {
      notification["error"]({
        message: t("jobs.errors.saving", {
          error: JSON.stringify(result.errors),
        }),
      });
    }
    setLoading(false);
  };

  return (
    <>
      <Button
        loading={loading}
        disabled={!job.date_exported}
        onClick={handleMarkForExport}
      >
        {t("jobs.labels.markforreexport")}
      </Button>
      <Button
        loading={loading}
        disabled={job.date_exported}
        onClick={handleMarkExported}
      >
        {t("jobs.actions.markasexported")}
      </Button>
      <Button
        loading={loading}
        disabled={!job.date_invoiced || job.date_exported}
        onClick={handleUninvoice}
      >
        {t("jobs.actions.uninvoice")}
      </Button>
    </>
  );
}
