import { useTreatmentsWithConfig } from "@splitsoftware/splitio-react";
import { Card, Col, Input, Row, Space, Typography } from "antd";
import _ from "lodash";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectPrintCenter } from "../../redux/modals/modals.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { TemplateList } from "../../utils/TemplateConstants";
import Jobd3RdPartyModal from "../job-3rd-party-modal/job-3rd-party-modal.component";
import PrintCenterItem from "../print-center-item/print-center-item.component";
import PrintCenterJobsLabels from "../print-center-jobs-labels/print-center-jobs-labels.component";
import PrintCenterSpeedPrint from "../print-center-speed-print/print-center-speed-print.component";
import { bodyshopHasDmsKey, DMS_MAP, getDmsMode } from "../../utils/dmsUtils";
import { selectTechnician } from "../../redux/tech/tech.selectors";

const mapStateToProps = createStructuredSelector({
  printCenterModal: selectPrintCenter,
  bodyshop: selectBodyshop,
  technician: selectTechnician
});

const mapDispatchToProps = () => ({});

export function PrintCenterJobsComponent({ printCenterModal, bodyshop, technician }) {
  const [search, setSearch] = useState("");
  const { id: jobId, job } = printCenterModal.context;
  const tempList = TemplateList("job", {});
  const { t } = useTranslation();
  const {
    treatments: { Enhanced_Payroll }
  } = useTreatmentsWithConfig({
    attributes: {},
    names: ["Enhanced_Payroll"],
    splitKey: bodyshop.imexshopid
  });
  const hasDMSKey = bodyshopHasDmsKey(bodyshop);
  const dmsMode = getDmsMode(bodyshop, "off");
  const isReynoldsMode = dmsMode === DMS_MAP.reynolds;

  const Templates = !hasDMSKey
    ? Object.keys(tempList)
        .map((key) => {
          return tempList[key];
        })
        .filter(
          (temp) =>
            (!temp.regions ||
              (temp.regions && temp.regions[bodyshop.region_config]) ||
              (temp.regions && bodyshop.region_config.includes(Object.keys(temp.regions)) === true)) &&
            (!temp.dms || temp.dms === false)
        )
        .filter((temp) => !technician || temp.group !== "financial")
    : Object.keys(tempList)
        .map((key) => {
          return tempList[key];
        })
        .filter(
          (temp) =>
            !temp.regions ||
            (temp.regions && temp.regions[bodyshop.region_config]) ||
            (temp.regions && bodyshop.region_config.includes(Object.keys(temp.regions)) === true)
        )
        .filter((temp) => !isReynoldsMode || !temp.excludedDmsModes?.includes(dmsMode))
        .filter((temp) => !technician || temp.group !== "financial");
        
  const JobsReportsList =
    Enhanced_Payroll.treatment === "on"
      ? Object.keys(Templates)
          .map((key) => {
            return Templates[key];
          })
          .filter((temp) => temp.enhanced_payroll === undefined || temp.enhanced_payroll === true)
      : Object.keys(Templates)
          .map((key) => {
            return Templates[key];
          })
          .filter((temp) => temp.enhanced_payroll === undefined || temp.enhanced_payroll === false);
  const filteredJobsReportsList =
    search !== ""
      ? JobsReportsList.filter((r) => r.title.toLowerCase().includes(search.toLowerCase()))
      : JobsReportsList;

  //Group it, create cards, and then filter out.

  const grouped = _.groupBy(filteredJobsReportsList, "group");

  return (
    <div>
      <Row gutter={[16, 16]}>
        <Col lg={8} md={12} sm={24}>
          <PrintCenterSpeedPrint jobId={jobId} />
        </Col>
        <Col lg={16} md={12} sm={24} className="print-center-list">
          <Card
            extra={
              <Space wrap>
                <PrintCenterJobsLabels jobId={jobId} />
                <Jobd3RdPartyModal jobId={jobId} job={job} />
                <Input.Search onChange={(e) => setSearch(e.target.value)} value={search} enterButton />
              </Space>
            }
          >
            <Row gutter={[16, 16]}>
              {Object.keys(grouped).map((key) => (
                <Col md={12} sm={24} key={key}>
                  <Card.Grid style={{ width: "100%", height: "100%" }}>
                    <Typography.Title level={4}>{t(`printcenter.labels.groups.${key}`)}</Typography.Title>
                    <ul //style={{ columns: "3 auto" }}
                    >
                      {grouped[key].map((item) => (
                        <PrintCenterItem key={item.key} item={item} id={jobId} disabled={item.disabled} />
                      ))}
                    </ul>
                  </Card.Grid>
                </Col>
              ))}
            </Row>
          </Card>
        </Col>
      </Row>
    </div>
  );
}

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