import { useTreatmentsWithConfig } from "@splitsoftware/splitio-react";
import { Button, Card, Col, Row, Space, Tooltip, Typography } from "antd";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectPrintCenter } from "../../redux/modals/modals.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { selectTechnician } from "../../redux/tech/tech.selectors";
import { TemplateList } from "../../utils/TemplateConstants";
import { GenerateDocument } from "../../utils/RenderTemplate";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";
import { HistoryOutlined, MailOutlined, PrinterOutlined, UnorderedListOutlined } from "@ant-design/icons";
import { bodyshopHasDmsKey } from "../../utils/dmsUtils.js";

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

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

export function PrintCenterJobsPartsComponent({ printCenterModal, bodyshop, technician }) {
  const { id: jobId, job } = printCenterModal.context;
  const tempList = TemplateList("job", {});
  const notification = useNotification();
  const {
    treatments: { Enhanced_Payroll }
  } = useTreatmentsWithConfig({
    attributes: {},
    names: ["Enhanced_Payroll"],
    splitKey: bodyshop.imexshopid
  });
  const hasDMSKey = bodyshopHasDmsKey(bodyshop);
  
  const Templates = !hasDMSKey
    ? Object.keys(tempList)
        .map((key) => tempList[key])
        .filter(
          (temp) =>
            (!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) => tempList[key])
        .filter(
          (temp) =>
            !temp.regions ||
            temp.regions?.[bodyshop.region_config] ||
            (temp.regions && bodyshop.region_config.includes(Object.keys(temp.regions)) === true)
        )
        .filter((temp) => !technician || temp.group !== "financial");
  
  const JobsReportsList =
    Enhanced_Payroll.treatment === "on"
      ? Object.keys(Templates)
          .map((key) => Templates[key])
          .filter((temp) => temp.enhanced_payroll === undefined || temp.enhanced_payroll === true)
      : Object.keys(Templates)
          .map((key) => Templates[key])
          .filter((temp) => temp.enhanced_payroll === undefined || temp.enhanced_payroll === false);

  const orderedKeys = ["parts_list", "parts_order_history"]; // explicit order
  const cards = orderedKeys.map((k) => JobsReportsList.find((t) => t.key === k)).filter(Boolean);

  const handlePrint = async (key) => {
    await GenerateDocument(
      {
        name: key,
        variables: { id: jobId }
      },
      {},
      "p",
      jobId,
      notification
    );
  };

  const handleEmail = async (key) => {
    await GenerateDocument(
      {
        name: key,
        variables: { id: jobId }
      },
      {
        to: job?.ownr_ea,
        subject: cards.find((c) => c.key === key)?.subject
      },
      "e",
      jobId,
      notification
    );
  };

  const iconForKey = (key) => {
    switch (key) {
      case "parts_list":
        return <UnorderedListOutlined style={{ fontSize: 28 }} />;
      case "parts_order_history":
        return <HistoryOutlined style={{ fontSize: 28 }} />;
      default:
        return <PrinterOutlined style={{ fontSize: 28 }} />;
    }
  };

  return (
    <div>
      <Row gutter={[16, 16]}>
        {cards.map((item) => {
          const actions = [
            {
              key: "print",
              icon: <PrinterOutlined />,
              onClick: () => handlePrint(item.key),
              title: "Print",
              disabled: item.disabled
            },
            ...(!technician
              ? [
                  {
                    key: "email",
                    icon: <MailOutlined />,
                    onClick: () => handleEmail(item.key),
                    title: "Email",
                    disabled: item.disabled
                  }
                ]
              : [])
          ];
          const columns = `repeat(${actions.length}, 1fr)`;

          return (
            <Col key={item.key} xs={24} sm={24} md={24} lg={24} xl={24}>
              <Card hoverable style={{ minHeight: 100 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <div style={{ flex: "1 1 70%", minWidth: 0 }}>
                    <Space align="center">
                      <div aria-hidden>{iconForKey(item.key)}</div>
                      <Typography.Title level={5} style={{ margin: 0 }}>
                        {item.title}
                      </Typography.Title>
                    </Space>
                  </div>
                  <div style={{ flex: "0 0 30%" }}>
                    <div
                      style={{
                        display: "grid",
                        gridTemplateColumns: columns,
                        gap: 8,
                        alignItems: "stretch"
                      }}
                    >
                      {actions.map((action) => (
                        <Tooltip key={action.key} title={action.title} placement="top">
                          <Button
                            icon={action.icon}
                            size="large"
                            onClick={action.onClick}
                            disabled={action.disabled}
                            aria-label={action.title}
                            style={{
                              width: "100%",
                              aspectRatio: "1 / 1",
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "center",
                              padding: 0
                            }}
                          />
                        </Tooltip>
                      ))}
                    </div>
                  </div>
                </div>
              </Card>
            </Col>
          );
        })}
      </Row>
    </div>
  );
}

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