import { Button, List } from "antd";
import { PageHeader } from "@ant-design/pro-layout";

import { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { GenerateDocuments } from "../../utils/RenderTemplate";
import { TemplateList } from "../../utils/TemplateConstants";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

export function PrintCenterSpeedPrint({ bodyshop, jobId }) {
  const [loading, setLoading] = useState(false);
  const { speedprint } = bodyshop;
  const { t } = useTranslation();
  const notification = useNotification();

  const renderAllTemplates = async (templateKeys) => {
    logImEXEvent("speed_print_render_all_templates");
    setLoading(true);
    await GenerateDocuments(
      templateKeys.map((key) => {
        return { name: key, variables: { id: jobId } };
      }),
      notification
    );
    setLoading(false);
  };

  return (
    <div>
      <PageHeader title={t("printcenter.labels.speedprint")} />

      <List
        itemLayout="horizontal"
        dataSource={speedprint}
        renderItem={(sp) => (
          <List.Item
            actions={[
              <Button
                key="printCenterSpeedPrintLoadingButton"
                loading={loading}
                onClick={() => renderAllTemplates(sp.templates)}
              >
                Print All
              </Button>
            ]}
          >
            <List.Item.Meta title={sp.label} description={renderTemplateList(sp.templates)} />
          </List.Item>
        )}
      />
    </div>
  );
}

const renderTemplateList = (templates) => {
  const TemplateListGenerated = TemplateList();
  return (
    <span className="imex-flex-row__margin">
      {templates.map((template, idx) => {
        if (idx === templates.length - 1)
          return (TemplateListGenerated[template] && TemplateListGenerated[template].title) || "";
        return `${(TemplateListGenerated[template] && TemplateListGenerated[template].title) || ""}, `;
      })}
    </span>
  );
};

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