import { useApolloClient } from "@apollo/client/react";
import { useTreatmentsWithConfig } from "@splitsoftware/splitio-react";
import { Button, Popconfirm } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { UPDATE_JOB_LINES_IOU } from "../../graphql/jobs-lines.queries";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";
import { CreateIouForJob } from "../jobs-detail-header-actions/jobs-detail-header-actions.duplicate.util";
import { selectTechnician } from "../../redux/tech/tech.selectors";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(JobCreateIOU);

export function JobCreateIOU({ bodyshop, currentUser, job, selectedJobLines, technician }) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const client = useApolloClient();
  const history = useNavigate();
  const notification = useNotification();

  const {
    treatments: { IOU_Tracking }
  } = useTreatmentsWithConfig({
    attributes: {},
    names: ["IOU_Tracking"],
    splitKey: bodyshop.imexshopid
  });

  if (IOU_Tracking.treatment !== "on") return null;

  const handleCreateIou = async () => {
    setLoading(true);
    //Query all of the job details to recreate.
    const iouId = await CreateIouForJob({
      apolloClient: client,
      jobLinesToKeep: selectedJobLines,
      jobId: job.id,
      config: {
        status: bodyshop.md_ro_statuses.default_open,
        bodyshopid: bodyshop.id,
        useremail: currentUser.email,
        timezone: bodyshop.timezone
      },
      currentUser
    });

    notification.success({
      title: t("jobs.successes.ioucreated"),
      onClick: () => history(`/manage/jobs/${iouId}`)
    });
    const selectedJobLinesIds = selectedJobLines.map((l) => l.id);
    await client.mutate({
      mutation: UPDATE_JOB_LINES_IOU,
      variables: { ids: selectedJobLinesIds },
      update(cache) {
        cache.modify({
          id: cache.identify(job.id),
          fields: {
            joblines(existingJobLines) {
              return existingJobLines.map((a) => {
                if (!selectedJobLinesIds.includes(a.id)) return a;
                return { ...a, ioucreated: true };
              });
            }
          }
        });
      }
    });

    setLoading(false);
  };

  return (
    <Popconfirm
      title={t("jobs.labels.createiouwarning")}
      onConfirm={handleCreateIou}
      disabled={!selectedJobLines || selectedJobLines.length === 0 || !job.converted || technician}
    >
      <Button
        loading={loading}
        disabled={!selectedJobLines || selectedJobLines.length === 0 || !job.converted || technician}
      >
        {t("jobs.actions.createiou")}
      </Button>
    </Popconfirm>
  );
}
