import { useApolloClient } from "@apollo/client/react";
import { Button, Form, Popover, Space } from "antd";
import axios from "axios";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";
import { GET_DOC_SIZE_BY_JOB } from "../../graphql/documents.queries.js";
import { selectBodyshop } from "../../redux/user/user.selectors.js";
import JobSearchSelect from "../job-search-select/job-search-select.component.jsx";
import { isFunction } from "lodash";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(JobsDocumentsImgproxyGalleryReassign);

/*
################################################################################################
 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 function JobsDocumentsImgproxyGalleryReassign({ bodyshop, galleryImages, callback }) {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const notification = useNotification();

  const selectedImages = useMemo(() => {
    return [
      ...galleryImages.images.filter((image) => image.isSelected),
      ...galleryImages.other.filter((image) => image.isSelected)
    ];
  }, [galleryImages]);
  const client = useApolloClient();
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);

  const handleFinish = async ({ jobid }) => {
    setLoading(true);

    //Check to see if the space remaining on the new job is sufficient. If it isn't cancel this.
    const newJobData = await client.query({
      query: GET_DOC_SIZE_BY_JOB,
      variables: { jobId: jobid }
    });

    const transferedDocSizeTotal = selectedImages.reduce((acc, val) => acc + val.size, 0);

    const shouldPreventTransfer =
      bodyshop.jobsizelimit - newJobData.data.documents_aggregate.aggregate.sum.size < transferedDocSizeTotal;

    if (shouldPreventTransfer) {
      notification.error({
        key: "cannotuploaddocuments",
        title: t("documents.labels.reassign_limitexceeded_title"),
        description: t("documents.labels.reassign_limitexceeded")
      });
      setLoading(false);
      return;
    }

    const res = await axios.post("/media/imgproxy/rename", {
      tojobid: jobid,
      documents: selectedImages.map((i) => {
        //Need to check if the current key folder is null, or another job.
        const currentKeys = i.key.split("/");
        currentKeys[1] = jobid;
        currentKeys.join("/");
        return {
          id: i.id,
          from: i.key,
          to: currentKeys.join("/"),
          extension: i.extension,
          type: i.type
        };
      })
    });
    //Add in confirmation & errors.
    if (isFunction(callback)) callback();

    if (res.errors) {
      notification.error({
        title: t("documents.errors.updating", {
          message: JSON.stringify(res.errors)
        })
      });
    }
    if (!res.mutationResult?.errors) {
      notification.success({
        message: t("documents.successes.updated")
      });
    }
    setOpen(false);
    setLoading(false);
  };

  const popContent = (
    <div>
      <Form onFinish={handleFinish} layout="vertical" form={form}>
        <Form.Item
          label={t("documents.labels.newjobid")}
          style={{ width: "20rem" }}
          rules={[
            {
              required: true
              //message: t("general.validation.required"),
            }
          ]}
          name={"jobid"}
        >
          <JobSearchSelect notExported={false} notInvoiced={false} />
        </Form.Item>
      </Form>
      <Space>
        <Button type="primary" onClick={() => form.submit()}>
          {t("general.actions.submit")}
        </Button>
        <Button onClick={() => setOpen(false)}>{t("general.actions.cancel")}</Button>
      </Space>
    </div>
  );

  return (
    <Popover content={popContent} open={open}>
      <Button disabled={selectedImages.length < 1} onClick={() => setOpen(true)} loading={loading}>
        {t("documents.actions.reassign")}
      </Button>
    </Popover>
  );
}
