import { useApolloClient } from "@apollo/client";
import { Button, Tooltip } from "antd";
import { antdMessage as message } from "../../../util/antdFeedback";
import { useState } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { QUERY_JOB_ESTIMATE_SCRUBBER } from "../../../graphql/jobs.queries";
import ipcTypes from "../../../ipc.types";
import { selectBodyshop } from "../../../redux/user/user.selectors";
const { ipcRenderer } = window;
const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
  bodyshop: selectBodyshop
});
const mapDispatchToProps = (dispatch) => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(EstimateScrubberButton);

export function EstimateScrubberButton({ bodyshop, jobid, job }) {
  const [loading, setLoading] = useState(false);
  const client = useApolloClient();
  const handleScrub = async () => {
    try {
      ipcRenderer.send(ipcTypes.app.toMain.track, {
        event: "SCRUB_ESTIMATE",
        jobId: jobid
      });
      setLoading(true);

      const jobData = await client.query({
        query: QUERY_JOB_ESTIMATE_SCRUBBER,
        variables: { jobId: jobid },
        fetchPolicy: "network-only"
      });

      const result = await ipcRenderer.invoke(ipcTypes.app.toMain.scrubEstimate, {
        job: jobData.data.jobs_by_pk
      });
      if (result) {
        message.success("Estimate scrubbed successfully! ");
        // Scroll to the estimate scrubber results section
        const scrollToResults = () => {
          const element = document.getElementById("es-results-card");
          if (element) {
            element.scrollIntoView({
              behavior: "smooth",
              block: "start",
              inline: "nearest"
            });
          }
        };

        // Small delay to ensure DOM is updated before scrolling
        setTimeout(scrollToResults, 100);
      }
    } catch (error) {
      message.error("Error scrubbing estimate: " + error.message);
      console.error("Error scrubbing estimate:", error);
    }
    setLoading(false);
  };

  const buttonDisabled = job?.g_bett_amt == null;

  return buttonDisabled ? (
    <Tooltip title="Additional information is required to scrub this estimate. Please reimport the estimate to enable scrubbing.">
      <Button disabled={buttonDisabled} loading={loading}>
        Scrub Estimate with Estimate Scrubber (BETA)
      </Button>
    </Tooltip>
  ) : (
    <Button onClick={handleScrub} disabled={buttonDisabled} loading={loading}>
      Scrub Estimate with Estimate Scrubber (BETA)
    </Button>
  );
}
