import { Button, List, PageHeader } from "antd";
import React, { 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";

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

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

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

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

      <List
        itemLayout="horizontal"
        dataSource={speedprint}
        renderItem={(sp) => (
          <List.Item
            actions={[
              <Button
                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);
