import { Button, Form, Modal } from "antd";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { toggleModalVisible } from "../../redux/modals/modals.actions";
import { selectCaBcEtfTableConvert } from "../../redux/modals/modals.selectors";
import { GenerateDocument } from "../../utils/RenderTemplate";
import { TemplateList } from "../../utils/TemplateConstants";
import CaBcEtfTableModalComponent from "./ca-bc-etf-table.modal.component";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

const mapStateToProps = createStructuredSelector({
  caBcEtfTableModal: selectCaBcEtfTableConvert
});

const mapDispatchToProps = (dispatch) => ({
  toggleModalVisible: () => dispatch(toggleModalVisible("ca_bc_eftTableConvert"))
});

export function ContractsFindModalContainer({ caBcEtfTableModal, toggleModalVisible }) {
  const { t } = useTranslation();

  const { open } = caBcEtfTableModal;
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const EtfTemplate = TemplateList("special").ca_bc_etf_table;
  const notification = useNotification();

  const handleFinish = async (values) => {
    logImEXEvent("ca_bc_etf_table_parse");
    setLoading(true);
    const claimNumbers = [];
    values.table.split("\n").forEach((row) => {
      const { 1: claim, 2: shortclaim, 4: amount } = row.split("\t");
      if (!claim || !shortclaim) return;
      const trimmedShortClaim = shortclaim.trim();
      // const trimmedClaim = claim.trim();
      if (amount.slice(-1) === "-") {
        // NO OP
      }

      claimNumbers.push({
        claim: trimmedShortClaim,
        amount: amount.slice(-1) === "-" ? parseFloat(amount) * -1 : amount
      });
    });

    await GenerateDocument(
      {
        name: EtfTemplate.key,
        variables: {
          claimNumbers: `%(${claimNumbers.map((c) => c.claim).join("|")})%`,
          claimdata: claimNumbers
        }
      },
      {},
      values.sendby === "email" ? "e" : "p",
      null,
      notification
    );
    setLoading(false);
  };

  useEffect(() => {
    if (open) {
      form.resetFields();
    }
  }, [open, form]);

  return (
    <Modal
      open={open}
      width="70%"
      title={t("payments.labels.findermodal")}
      onCancel={() => toggleModalVisible()}
      onOk={() => toggleModalVisible()}
      destroyOnHidden
      forceRender
    >
      <Form form={form} layout="vertical" autoComplete="no" onFinish={handleFinish}>
        <CaBcEtfTableModalComponent form={form} />
        <Button onClick={() => form.submit()} type="primary" loading={loading}>
          {t("general.labels.search")}
        </Button>
      </Form>
    </Modal>
  );
}

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