import { IconButton, Tooltip } from "@mui/material";
import React, { useState, useRef } from "react";
import { BsFillFileEarmarkPdfFill } from "react-icons/bs";
import { useReactToPrint } from "react-to-print";
import ProvinceAllcationInvoice from "../province-allocation-invoice/ProvinceAllcationInvoice";
import { useDispatch } from "react-redux";
import { provinceGetAllocationLetter } from "../../services/province-get-allocation-letter";
import { useEffect } from "react";
import { PropTypes } from "prop-types";

export const ProvinceAllocatedRequestsInvoiceOperation = ({ date1, date2 }) => {
  const dispatch = useDispatch();
  const [factorData, setFactorData] = useState(null);
  const componentRef = useRef();

  const handleDownloadFactor = () => {
    const result = dispatch(provinceGetAllocationLetter(date1));
    setFactorData(result);
  };

  const printPDF = useReactToPrint({
    content: () => componentRef.current,
    documentTitle: "گزارش روزانه",
    onAfterPrint: () => {
      setFactorData(null);
    },
  });

  useEffect(() => {
    if (factorData) {
      printPDF();
    }
  }, [factorData, printPDF]);

  return (
    <div>
      <Tooltip title="خروجی PDF">
        <IconButton
          disabled={date2 && date1 !== date2}
          onClick={() => {
            handleDownloadFactor();
          }}
          size={"large"}
          aria-label="delete"
          color="success"
        >
          <BsFillFileEarmarkPdfFill size={32} />
        </IconButton>
      </Tooltip>
      <div style={{ visibility: "hidden", position: "absolute" }}>
        <ProvinceAllcationInvoice
          ref={componentRef}
          item={factorData?.payload?.data}
          date={date1}
        />
      </div>
    </div>
  );
};

ProvinceAllocatedRequestsInvoiceOperation.propTypes = {
  date1: PropTypes.any,
  date2: PropTypes.any,
};
