import { PrinterFilled, WarningOutlined } from "@ant-design/icons";
import { PageHeader } from "@ant-design/pro-layout";
import { Alert, Button, Descriptions, Skeleton, Space, Tooltip } from "antd";
import moment from "moment";
import { useMemo, useRef } from "react";
import { useReactToPrint } from "react-to-print";
import { DateFormat, WhichMPIRulesetToApply } from "../../../util/constants";
import dayjs from "../../../util/day.js";
import CurrencyFormatterAtom from "../../atoms/currency-formatter/currency-formatter.atom";
import DeleteJobAtom from "../../atoms/delete-job/delete-job.atom";
import ErrorResultAtom from "../../atoms/error-result/error-result.atom";
import TimeAgoFormatter from "../../atoms/time-ago-formatter/time-ago-formatter.atom";
import VehicleGroupAlertAtom from "../../atoms/vehicle-group-alert/vehicle-group-alert.atom";
import CloseDateDisplayMolecule from "../close-date-display/close-date-display.molecule";
import JobGroupMolecule from "../job-group/job-group.molecule";
import EstimateScrubberButton from "../estimate-scrubber-button/estimate-scrubber-button.molecule.jsx";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../../redux/user/user.selectors.js";
import { connect } from "react-redux";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
export default connect(mapStateToProps, null)(JobsDetailDescriptionMolecule);

export function JobsDetailDescriptionMolecule({ bodyshop, loading, job, jobDetailRef }) {
  // Store original theme state
  const originalThemeRef = useRef(null);

  const handlePrint = useReactToPrint({
    contentRef: jobDetailRef,
    bodyClass: "audit-container-print",
    onBeforeGetContent: () => {
      // Store original theme state
      originalThemeRef.current = {
        dataTheme: document.documentElement.getAttribute("data-theme"),
        bodyClasses: Array.from(document.body.classList),
        htmlClasses: Array.from(document.documentElement.classList)
      };

      // Force light mode for printing
      document.documentElement.setAttribute("data-theme", "light");
      document.body.classList.remove("dark", "ant-dark");
      document.documentElement.classList.remove("dark", "ant-dark");

      // Set light mode CSS variables for Ant Design
      document.documentElement.style.setProperty("--ant-color-bg-base", "#ffffff");
      document.documentElement.style.setProperty("--ant-color-text", "#000000");
      document.documentElement.style.setProperty("--ant-color-text-secondary", "rgba(0, 0, 0, 0.65)");
      document.documentElement.style.setProperty("--ant-color-border", "#d9d9d9");
    },
    onAfterPrint: () => {
      // Restore original theme after printing
      if (originalThemeRef.current) {
        const { dataTheme, bodyClasses, htmlClasses } = originalThemeRef.current;

        if (dataTheme) {
          document.documentElement.setAttribute("data-theme", dataTheme);
        } else {
          document.documentElement.removeAttribute("data-theme");
        }

        // Restore original classes
        document.body.className = bodyClasses.join(" ");
        document.documentElement.className = htmlClasses.join(" ");
      }

      // Reset CSS variables
      document.documentElement.style.removeProperty("--ant-color-bg-base");
      document.documentElement.style.removeProperty("--ant-color-text");
      document.documentElement.style.removeProperty("--ant-color-text-secondary");
      document.documentElement.style.removeProperty("--ant-color-border");
    }
  });

  if (loading) return <Skeleton active />;
  if (!job)
    return (
      <ErrorResultAtom title="Error displaying job header data." errorMessage="It looks like this job doesn't exist." />
    );
  const MPIRulesetToApply = WhichMPIRulesetToApply(job.close_date);

  return (
    <PageHeader
      title={job.clm_no}
      subTitle={job.ins_co_nm}
      extra={[
        job.requires_reimport && (
          <Tooltip
            key="reimport"
            title="There are different rules that apply for claims submitted in different periods. In order to ensure accurate calculation, you must import this job again to determine which parts are eligible for parts autonomy. This happened because the close date was changed between these periods."
          >
            <Alert
              type="warning"
              showIcon
              message="RPS has detected this job may have inaccurate grouping/targets. Reimport this job for accurate scoring."
            />
          </Tooltip>
        ),
        bodyshop.es_api_key && <EstimateScrubberButton key="es" jobid={job ? job.id : null} job={job ? job : null} />,
        <DeleteJobAtom key="delete" jobId={job.id} />,
        <Button key="print" onClick={handlePrint}>
          <PrinterFilled />
        </Button>
      ]}
    >
      <Descriptions column={{ xxl: 5, xl: 4, lg: 3, md: 2, sm: 1, xs: 1 }}>
        <Descriptions.Item label="Owner">{`${job.ownr_fn} ${job.ownr_ln}`}</Descriptions.Item>
        <Descriptions.Item label="Vehicle">
          <VehicleGroupAlertAtom job={job} />
        </Descriptions.Item>
        <Descriptions.Item label="Claim Total">
          <CurrencyFormatterAtom>{job.clm_total}</CurrencyFormatterAtom>
        </Descriptions.Item>
        <Descriptions.Item label="Group">
          <JobGroupMolecule jobId={job.id} group={job.group} job={job} />
        </Descriptions.Item>
        <Descriptions.Item label="Age">{job.v_age}</Descriptions.Item>
        <Descriptions.Item
          label={
            <Tooltip title="This is the date you will submit for payment. This should always be the latest date in the case of supplements.">
              Close Date
            </Tooltip>
          }
        >
          <CloseDateDisplayMolecule job={job} jobId={job.id} close_date={job.close_date} />
        </Descriptions.Item>
        <Descriptions.Item label="Last Updated">
          <Tooltip title={`First Created ${moment(job.created_at).format("MM/DD/YY")}`}>
            <TimeAgoFormatter>{job.updated_at}</TimeAgoFormatter>
          </Tooltip>
        </Descriptions.Item>
        <Descriptions.Item label="# RPS Eligible Parts">
          {job && job.joblines.filter((i) => !i.ignore && i.db_ref !== "900511").length}
        </Descriptions.Item>
        <Descriptions.Item label="Loss Date">
          {job.loss_date ? dayjs(job.loss_date).format(DateFormat) : "No Loss Date"}
        </Descriptions.Item>
        <Descriptions.Item label="Mileage">
          <Space size="small">
            {job.v_mileage}
            {bodyshop?.ins_rule_set === "MPI" && MPIRulesetToApply === "V3" && job.v_mileage < 20000 && (
              <Tooltip title="Vehicle is under 20,000 KMs. No expected savings.">
                <WarningOutlined style={{ color: "seagreen" }} />
              </Tooltip>
            )}
          </Space>
        </Descriptions.Item>
      </Descriptions>
    </PageHeader>
  );
}
