import { Button, Typography, List } from "antd";
import React 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 RenderTemplate, {
  displayTemplateInWindow,
} 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 { speedprint } = bodyshop;
  const { t } = useTranslation();
  const renderTemplate = async (templateKey) => {
    logImEXEvent("speed_print_template_render");

    const html = await RenderTemplate(
      {
        name: templateKey,
        variables: { id: jobId },
      },
      bodyshop
    );
    displayTemplateInWindow(html);
  };

  const renderAllTemplates = (templateKeys) => {
    logImEXEvent("speed_print_render_all_templates");

    templateKeys.forEach((templateKey) => renderTemplate(templateKey));
  };

  return (
    <div>
      <Typography.Title level={2}>
        {t("printcenter.labels.speedprint")}
      </Typography.Title>

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

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

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