import { UploadOutlined } from "@ant-design/icons";
import { Button, Upload } from "antd";
import axios from "axios";
import { 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 { setModalContext } from "../../redux/modals/modals.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { hasDocumensoApiKey } from "../../utils/esignature.js";

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

const mapDispatchToProps = (dispatch) => ({
  setEsignatureContext: (context) =>
    dispatch(
      setModalContext({
        context,
        modal: "esignature"
      })
    )
});

export function EsignatureCustomDocument({ bodyshop, jobId, setEsignatureContext }) {
  const [loading, setLoading] = useState(false);
  const notification = useNotification();
  const { t } = useTranslation();

  if (!hasDocumensoApiKey(bodyshop)) {
    return null;
  }

  const uploadCustomDocument = async ({ file, onError, onSuccess }) => {
    const formData = new FormData();
    formData.append("document", file);
    formData.append("jobid", jobId);
    formData.append("bodyshop", JSON.stringify(bodyshop));

    setLoading(true);

    try {
      const {
        data: { token, documentId, envelopeId }
      } = await axios.post("/esign/new-custom", formData, {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      });

      setEsignatureContext({ context: { token, documentId, envelopeId, jobid: jobId } });
      onSuccess?.({ token, documentId, envelopeId });
    } catch (error) {
      notification.error({
        title: t("esignature.errors.upload_title"),
        description: error?.response?.data?.error || error?.response?.data?.message || error.message
      });
      onError?.(error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Upload
      accept="application/pdf,.pdf"
      beforeUpload={(file) => {
        if (file.type === "application/pdf" || file.name?.toLowerCase().endsWith(".pdf")) {
          return true;
        }

        notification.error({
          title: t("esignature.errors.upload_title"),
          description: t("esignature.errors.pdf_only")
        });
        return Upload.LIST_IGNORE;
      }}
      customRequest={uploadCustomDocument}
      maxCount={1}
      showUploadList={false}
      multiple={false}
    >
      <Button icon={<UploadOutlined />} loading={loading}>
        {t("esignature.actions.upload_document")}
      </Button>
    </Upload>
  );
}

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