import { useQuery } from "@apollo/client";
import { Badge, Button, Card, Result, Skeleton } from "antd";
import { useEffect, useRef, useState } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { QUERY_JOB_BY_PK } from "../../../graphql/jobs.queries";
import { setSelectedJobTargetPc } from "../../../redux/application/application.actions";
import { selectSelectedJobId } from "../../../redux/application/application.selectors";
import { selectBodyshop } from "../../../redux/user/user.selectors";
import ErrorResultAtom from "../../atoms/error-result/error-result.atom";
import JobsPartsGraphAtom from "../../atoms/jobs-parts-graph/jobs-parts-graph.atom";
import EstimateScrubberResultsMolecule from "../../molecules/estimate-scruber-results/estimate-scrubber-results.molecule";
import JobsDetailDescriptionMolecule from "../../molecules/jobs-detail-description/jobs-detail-description.molecule";
import JobsLinesTableMolecule from "../../molecules/jobs-lines-table/jobs-lines-table.molecule";
import JobsTargetsStatsMolecule from "../../molecules/jobs-targets-stats/jobs-targets-stats.molecule";
import ipcTypes from "../../../ipc.types";
import "./jobs-detail.organism.styles.scss";

const JOB_SELECTION_DEBOUNCE_MS = 120;

const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
  selectedJobId: selectSelectedJobId,
  bodyshop: selectBodyshop
});
const mapDispatchToProps = (dispatch) => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
  setSelectedJobTargetPc: (job) => dispatch(setSelectedJobTargetPc(job))
});

function useDebouncedSelectedJobId(selectedJobId) {
  const [debouncedSelectedJobId, setDebouncedSelectedJobId] = useState(selectedJobId);

  useEffect(() => {
    if (!selectedJobId) {
      setDebouncedSelectedJobId(selectedJobId);
      return undefined;
    }

    const timeoutId = setTimeout(() => {
      setDebouncedSelectedJobId(selectedJobId);
    }, JOB_SELECTION_DEBOUNCE_MS);

    return () => clearTimeout(timeoutId);
  }, [selectedJobId]);

  return debouncedSelectedJobId;
}

function JobDetailSkeleton() {
  return (
    <div className="jobs-detail-container">
      <Card>
        <Skeleton active paragraph={{ rows: 4 }} />
      </Card>
    </div>
  );
}

export function JobsDetailOrganism({ bodyshop, selectedJobId, setSelectedJobTargetPc }) {
  const debouncedSelectedJobId = useDebouncedSelectedJobId(selectedJobId);
  const { loading, error, data } = useQuery(QUERY_JOB_BY_PK, {
    variables: { jobId: debouncedSelectedJobId },
    skip: !debouncedSelectedJobId
  });
  const jobDetailRef = useRef();
  const job = data?.jobs_by_pk;
  const isSelectionPending = selectedJobId !== debouncedSelectedJobId;
  const hasSelectedJobData = job?.id === debouncedSelectedJobId;
  const isMissingSelectedJob = !isSelectionPending && !loading && debouncedSelectedJobId && !job;
  const isJobDetailLoading = isSelectionPending || loading || (job && !hasSelectedJobData);

  useEffect(() => {
    if (hasSelectedJobData)
      setSelectedJobTargetPc({
        group: job.group,
        v_age: job.v_age,
        close_date: job.close_date,
        v_mileage: job.v_mileage,
        job
      });
  }, [hasSelectedJobData, job, setSelectedJobTargetPc]);
  const isSgi = bodyshop?.ins_rule_set === "SGI";
  if (!selectedJobId)
    return (
      <div
        style={{
          display: "flex",
          height: "100%",
          justifyContent: "center",
          alignItems: "center"
        }}
      >
        <Result title="No job selected." />
      </div>
    );
  if (isJobDetailLoading) return <JobDetailSkeleton />;
  if (error) return <ErrorResultAtom title="Error fetching Job details.." errorMessage={JSON.stringify(error)} />;
  if (isMissingSelectedJob)
    return <ErrorResultAtom title="Error displaying job details." errorMessage="It looks like this job doesn't exist." />;

  return (
    <div ref={jobDetailRef} className="jobs-detail-container">
      <style type="text/css" media="print">
        {
          "\
  @page { size: landscape; }\
"
        }
      </style>
      <Card>
        <JobsDetailDescriptionMolecule
          loading={false}
          job={job}
          jobDetailRef={jobDetailRef}
        />
      </Card>
      <Card title="Job Targets">
        <JobsTargetsStatsMolecule loading={false} job={job} />
      </Card>

      {/* <JobsClaimClerk loading={loading} job={data ? data.jobs_by_pk : null} />
      //2025-05-27 Removing CC AI
       */}

      <Card title="Estimate Lines">
        <JobsLinesTableMolecule loading={false} job={job} />
      </Card>
      {bodyshop.es_api_key ? (
        <Badge.Ribbon text="BETA" color="red">
          <Card id="es-results-card" title="Estimate Scrubber Results" extra={[]}>
            <EstimateScrubberResultsMolecule loading={false} job={job} />
          </Card>
        </Badge.Ribbon>
      ) : (
        <Badge.Ribbon text={isSgi ? "COMING SOON" : null} color="red">
          <Card title="Estimate Scrubber">
            <Result
              status="info"
              title="Are you missing out on profit?"
              subTitle={`Estimate Scrubber identifies additional billing opportunities and potential issues with your estimates to help maximize your revenue. ${isSgi ? `Direct integration coming soon for Saskatchewan based users.` : "Get started with a free 30 day trial today."}`}
              extra={
                <Button
                  type="primary"
                  disabled={isSgi}
                  onClick={() => {
                    const { ipcRenderer } = window;
                    ipcRenderer.send(
                      ipcTypes.app.toMain.openExternalWindow,
                      "https://atamb.ca/estimate-scrubber-trial?utm_source=imex_rps&utm_medium=app&utm_campaign=es_trial_banner"
                    );
                  }}
                >
                 {isSgi ? "Integration coming soon" : "Get Started"}
                </Button>
              }
            ></Result>
          </Card>
        </Badge.Ribbon>
      )}
      <Card title="Parts Breakdown">
        <div
          style={{
            display: "flex",
            justifyContent: "space-evenly",
            minHeight: "20rem",
            width: "100%"
          }}
        >
          <JobsPartsGraphAtom job={job} loading={false} price="db_price" />
          <JobsPartsGraphAtom job={job} loading={false} />
        </div>
      </Card>
    </div>
  );
}
export default connect(mapStateToProps, mapDispatchToProps)(JobsDetailOrganism);
