import { PrinterFilled } from "@ant-design/icons";
import { Button, Card, List } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router-dom";
import { logImEXEvent } from "../../../../firebase/firebase.utils";
import { GenerateDocument, GenerateDocuments } from "../../../../utils/RenderTemplate";
import { TemplateList } from "../../../../utils/TemplateConstants";
import { useNotification } from "../../../../contexts/Notifications/notificationContext.jsx";

const TemplateListGenerated = TemplateList();

export default function JobIntakeTemplateList({ templates }) {
  const { jobId } = useParams();
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const notification = useNotification();

  const renderTemplate = async (templateKey) => {
    setLoading(true);
    logImEXEvent("job_checklist_template_render");

    await GenerateDocument(
      {
        name: templateKey,
        variables: { id: jobId }
      },
      {},
      "p",
      null,
      notification
    );
    setLoading(false);
  };

  const renderAllTemplates = async () => {
    logImEXEvent("checklist_render_all_templates");
    setLoading(true);

    await GenerateDocuments(
      templates.map((key) => {
        return { name: key, variables: { id: jobId } };
      }),
      notification
    );
    setLoading(false);
  };

  return (
    <Card
      title={t("jobs.labels.checklistdocuments")}
      extra={
        <Button onClick={renderAllTemplates} loading={loading}>
          {t("checklist.actions.printall")}
        </Button>
      }
    >
      <List
        itemLayout="horizontal"
        dataSource={templates}
        renderItem={(template) => (
          <List.Item
            actions={[
              <Button
                key="checkListTemplateButton"
                loading={loading}
                onClick={() => renderTemplate(template)}
                icon={<PrinterFilled />}
              />
            ]}
          >
            <List.Item.Meta
              title={TemplateListGenerated[template] && TemplateListGenerated[template].title}
              // description={renderTemplateList(template.templates)}
            />
          </List.Item>
        )}
      />
    </Card>
  );
}
