import { Button, Form, Popover, Space } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
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 cleanAxios from "../../utils/CleanAxios";
import JobSearchSelect from "../job-search-select/job-search-select.component";

const mapStateToProps = createStructuredSelector({
  allMedia: selectAllMedia,
  bodyshop: selectBodyshop
});
const mapDispatchToProps = (dispatch) => ({
  getJobMedia: (id) => dispatch(getJobMedia(id))

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

export function JobsDocumentsLocalGalleryReassign({ bodyshop, jobid, allMedia, getJobMedia }) {
  const { t } = useTranslation();
  const [form] = Form.useForm();

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

  const handleFinish = async ({ jobid: newJobid }) => {
    setLoading(true);
    const selectedDocuments = allMedia[jobid].filter((m) => m.isSelected);

    await cleanAxios.post(
      `${bodyshop.localmediaserverhttp}/jobs/move`,
      {
        from_jobid: jobid,
        jobid: newJobid,
        files: selectedDocuments.map((f) => f.filename)
      },
      { headers: { ims_token: bodyshop.localmediatoken } }
    );

    getJobMedia(jobid);
    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>
  );
}
