import { MailOutlined, PrinterOutlined } from "@ant-design/icons";
import { Space, Spin } from "antd";
import { useState } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectPrintCenter } from "../../redux/modals/modals.selectors";
import { selectTechnician } from "../../redux/tech/tech.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { GenerateDocument } from "../../utils/RenderTemplate";
import LockWrapperComponent from "../lock-wrapper/lock-wrapper.component";
import { HasFeatureAccess } from "./../feature-wrapper/feature-wrapper.component";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

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

export function PrintCenterItemComponent({ printCenterModal, item, id, bodyshop, disabled, technician }) {
  const [loading, setLoading] = useState(false);
  const { context } = printCenterModal;
  const notification = useNotification();

  const renderToNewWindow = async () => {
    setLoading(true);
    await GenerateDocument(
      {
        name: item.key,
        variables: { id: id }
      },
      {},
      "p",
      null,
      notification
    );
    setLoading(false);
  };

  if (
    disabled ||
    (item.featureNameRestricted && !HasFeatureAccess({ featureName: item.featureNameRestricted, bodyshop }))
  )
    return (
      <li className="print-center-item">
        <LockWrapperComponent featureName={item.featureNameRestricted} bodyshop={bodyshop}>
          {item.title}
        </LockWrapperComponent>
      </li>
    );
  return (
    <li>
      <Space wrap>
        {item.title}
        <PrinterOutlined onClick={renderToNewWindow} />
        {!technician ? (
          <MailOutlined
            onClick={() => {
              GenerateDocument(
                {
                  name: item.key,
                  variables: { id: id }
                },
                {
                  to: context.job?.ownr_ea,
                  subject: item.subject
                },
                "e",
                id,
                notification
              );
            }}
          />
        ) : null}
        {loading && <Spin />}
      </Space>
    </li>
  );
}

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